[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/backup/ -> lib.php (source)

   1  <?php //$Id: lib.php,v 1.89.2.7 2008/06/12 11:06:57 jmg324 Exp $
   2      //This file contains all the general function needed (file manipulation...)
   3      //not directly part of the backup/restore utility
   4  
   5      require_once($CFG->dirroot.'/lib/uploadlib.php');
   6  
   7      //Sets a name/value pair in backup_config table
   8      function backup_set_config($name, $value) {
   9          if (get_field("backup_config", "name", "name", $name)) {
  10              return set_field("backup_config", "value", addslashes($value), "name", $name);
  11          } else {
  12              $config = new object();
  13              $config->name = $name;
  14              $config->value = addslashes($value);
  15              return insert_record("backup_config", $config);
  16          }
  17      }
  18  
  19      //Gets all the information from backup_config table
  20      function backup_get_config() {
  21          $backup_config = null;
  22          if ($configs = get_records("backup_config")) {
  23              foreach ($configs as $config) {
  24                  $backup_config[$config->name] = $config->value;
  25              }
  26          }
  27          return (object)$backup_config;
  28      }
  29  
  30      //Delete old data in backup tables (if exists)
  31      //Four hours seem to be appropiate now that backup is stable
  32      function backup_delete_old_data() {
  33  
  34          global $CFG;
  35  
  36          //Change this if you want !!
  37          $hours = 4;
  38          //End change this
  39          $seconds = $hours * 60 * 60;
  40          $delete_from = time()-$seconds;
  41          //Now delete from tables
  42          $status = execute_sql("DELETE FROM {$CFG->prefix}backup_ids
  43                                 WHERE backup_code < '$delete_from'",false);
  44          if ($status) {
  45              $status = execute_sql("DELETE FROM {$CFG->prefix}backup_files
  46                                     WHERE backup_code < '$delete_from'",false);
  47          }
  48          //Now, delete old directory (if exists)
  49          if ($status) {
  50              $status = backup_delete_old_dirs($delete_from);
  51          }
  52          return($status);
  53      }
  54  
  55      //Function to delete dirs/files into temp/backup directory
  56      //older than $delete_from
  57      function backup_delete_old_dirs($delete_from) {
  58  
  59          global $CFG;
  60  
  61          $status = true;
  62          //Get files and directories in the temp backup dir witout descend
  63          $list = get_directory_list($CFG->dataroot."/temp/backup", "", false, true, true);
  64          foreach ($list as $file) {
  65              $file_path = $CFG->dataroot."/temp/backup/".$file;
  66              $moddate = filemtime($file_path);
  67              if ($status && $moddate < $delete_from) {
  68                  //If directory, recurse
  69                  if (is_dir($file_path)) {
  70                      $status = delete_dir_contents($file_path);
  71                      //There is nothing, delete the directory itself
  72                      if ($status) {
  73                          $status = rmdir($file_path);
  74                      }
  75                  //If file
  76                  } else {
  77                      unlink("$file_path");
  78                  }
  79              }
  80          }
  81  
  82          return $status;
  83      }
  84  
  85      //Function to check and create the needed dir to
  86      //save all the backup
  87      function check_and_create_backup_dir($backup_unique_code) {
  88  
  89          global $CFG;
  90  
  91          $status = check_dir_exists($CFG->dataroot."/temp",true);
  92          if ($status) {
  93              $status = check_dir_exists($CFG->dataroot."/temp/backup",true);
  94          }
  95          if ($status) {
  96              $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code,true);
  97          }
  98  
  99          return $status;
 100      }
 101  
 102      //Function to delete all the directory contents recursively
 103      //it supports a excluded dit too
 104      //Copied from the web !!
 105      function delete_dir_contents ($dir,$excludeddir="") {
 106  
 107          if (!is_dir($dir)) {
 108              // if we've been given a directory that doesn't exist yet, return true.
 109              // this happens when we're trying to clear out a course that has only just
 110              // been created.
 111              return true;
 112          }
 113          $slash = "/";
 114  
 115          // Create arrays to store files and directories
 116          $dir_files      = array();
 117          $dir_subdirs    = array();
 118  
 119          // Make sure we can delete it
 120          chmod($dir, 0777);
 121  
 122          if ((($handle = opendir($dir))) == FALSE) {
 123              // The directory could not be opened
 124              return false;
 125          }
 126  
 127          // Loop through all directory entries, and construct two temporary arrays containing files and sub directories
 128          while(false !== ($entry = readdir($handle))) {
 129              if (is_dir($dir. $slash .$entry) && $entry != ".." && $entry != "." && $entry != $excludeddir) {
 130                  $dir_subdirs[] = $dir. $slash .$entry;
 131              }
 132              else if ($entry != ".." && $entry != "." && $entry != $excludeddir) {
 133                  $dir_files[] = $dir. $slash .$entry;
 134              }
 135          }
 136  
 137          // Delete all files in the curent directory return false and halt if a file cannot be removed
 138          for($i=0; $i<count($dir_files); $i++) {
 139              chmod($dir_files[$i], 0777);
 140              if (((unlink($dir_files[$i]))) == FALSE) {
 141                  return false;
 142              }
 143          }
 144  
 145          // Empty sub directories and then remove the directory
 146          for($i=0; $i<count($dir_subdirs); $i++) {
 147              chmod($dir_subdirs[$i], 0777);
 148              if (delete_dir_contents($dir_subdirs[$i]) == FALSE) {
 149                  return false;
 150              }
 151              else {
 152                  if (remove_dir($dir_subdirs[$i]) == FALSE) {
 153                  return false;
 154                  }
 155              }
 156          }
 157  
 158          // Close directory
 159          closedir($handle);
 160  
 161          // Success, every thing is gone return true
 162          return true;
 163      }
 164  
 165      //Function to clear (empty) the contents of the backup_dir
 166      function clear_backup_dir($backup_unique_code) {
 167  
 168          global $CFG;
 169  
 170          $rootdir = $CFG->dataroot."/temp/backup/".$backup_unique_code;
 171  
 172          //Delete recursively
 173          $status = delete_dir_contents($rootdir);
 174  
 175          return $status;
 176      }
 177  
 178      //Returns the module type of a course_module's id in a course
 179      function get_module_type ($courseid,$moduleid) {
 180  
 181          global $CFG;
 182  
 183          $results = get_records_sql ("SELECT cm.id, m.name
 184                                      FROM {$CFG->prefix}course_modules cm,
 185                                           {$CFG->prefix}modules m
 186                                      WHERE cm.course = '$courseid' AND
 187                                            cm.id = '$moduleid' AND
 188                                            m.id = cm.module");
 189  
 190          if ($results) {
 191              $name = $results[$moduleid]->name;
 192          } else {
 193              $name = false;
 194          }
 195          return $name;
 196      }
 197  
 198      //This function return the names of all directories under a give directory
 199      //Not recursive
 200      function list_directories ($rootdir) {
 201  
 202          $results = null;
 203  
 204          $dir = opendir($rootdir);
 205          while (false !== ($file=readdir($dir))) {
 206              if ($file=="." || $file=="..") {
 207                  continue;
 208              }
 209              if (is_dir($rootdir."/".$file)) {
 210                  $results[$file] = $file;
 211              }
 212          }
 213          closedir($dir);
 214          return $results;
 215      }
 216  
 217      //This function return the names of all directories and files under a give directory
 218      //Not recursive
 219      function list_directories_and_files ($rootdir) {
 220  
 221          $results = "";
 222  
 223          $dir = opendir($rootdir);
 224          while (false !== ($file=readdir($dir))) {
 225              if ($file=="." || $file=="..") {
 226                  continue;
 227              }
 228              $results[$file] = $file;
 229          }
 230          closedir($dir);
 231          return $results;
 232      }
 233  
 234      //This function clean data from backup tables and
 235      //delete all temp files used
 236      function clean_temp_data ($preferences) {
 237  
 238          global $CFG;
 239  
 240          $status = true;
 241  
 242          //true->do it, false->don't do it. To debug if necessary.
 243          if (true) {
 244              //Now delete from tables
 245              $status = execute_sql("DELETE FROM {$CFG->prefix}backup_ids
 246                                     WHERE backup_code = '$preferences->backup_unique_code'",false);
 247              if ($status) {
 248                  $status = execute_sql("DELETE FROM {$CFG->prefix}backup_files
 249                                         WHERE backup_code = '$preferences->backup_unique_code'",false);
 250              }
 251              //Now, delete temp directory (if exists)
 252              $file_path = $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code;
 253              if (is_dir($file_path)) {
 254                  $status = delete_dir_contents($file_path);
 255                  //There is nothing, delete the directory itself
 256                  if ($status) {
 257                      $status = rmdir($file_path);
 258                  }
 259              }
 260          }
 261          return $status;
 262      }
 263  
 264      // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 265      // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 266      //This functions are used to copy any file or directory ($from_file)
 267      //to a new file or directory ($to_file). It works recursively and
 268      //mantains file perms.
 269      //I've copied it from: http://www.php.net/manual/en/function.copy.php
 270      //Little modifications done
 271  
 272      function backup_copy_file ($from_file,$to_file,$log_clam=false) {
 273  
 274          global $CFG;
 275  
 276          if (is_file($from_file)) {
 277              //echo "<br />Copying ".$from_file." to ".$to_file;              //Debug
 278              //$perms=fileperms($from_file);
 279              //return copy($from_file,$to_file) && chmod($to_file,$perms);
 280              umask(0000);
 281              if (copy($from_file,$to_file)) {
 282                  chmod($to_file,$CFG->directorypermissions);
 283                  if (!empty($log_clam)) {
 284                      clam_log_upload($to_file,null,true);
 285                  }
 286                  return true;
 287              }
 288              return false;
 289          }
 290          else if (is_dir($from_file)) {
 291              return backup_copy_dir($from_file,$to_file);
 292          }
 293          else{
 294              //echo "<br />Error: not file or dir ".$from_file;               //Debug
 295              return false;
 296          }
 297      }
 298  
 299      function backup_copy_dir($from_file,$to_file) {
 300  
 301          global $CFG;
 302  
 303          $status = true; // Initialize this, next code will change its value if needed
 304  
 305          if (!is_dir($to_file)) {
 306              //echo "<br />Creating ".$to_file;                                //Debug
 307              umask(0000);
 308              $status = mkdir($to_file,$CFG->directorypermissions); 
 309          }
 310          $dir = opendir($from_file);
 311          while (false !== ($file=readdir($dir))) {
 312              if ($file=="." || $file=="..") {
 313                  continue;
 314              }
 315              $status = backup_copy_file ("$from_file/$file","$to_file/$file");
 316          }
 317          closedir($dir);
 318          return $status;
 319      }
 320      ///Ends copy file/dirs functions
 321      // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 322      // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 323  
 324  
 325      function upgrade_backup_db($continueto) {
 326      /// This function upgrades the backup tables, if necessary
 327      /// It's called from admin/index.php, also backup.php and restore.php
 328  
 329          global $CFG, $db;
 330  
 331          require_once ("$CFG->dirroot/backup/version.php");  // Get code versions
 332  
 333          if (empty($CFG->backup_version)) {                  // Backup has never been installed.
 334              $strdatabaseupgrades = get_string("databaseupgrades");
 335              $navlinks = array();
 336              $navlinks[] = array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc');
 337              $navigation = build_navigation($navlinks);
 338  
 339              print_header($strdatabaseupgrades, $strdatabaseupgrades, $navigation, "",
 340                      upgrade_get_javascript(), false, "&nbsp;", "&nbsp;");
 341  
 342              upgrade_log_start();
 343              print_heading('backup');
 344              $db->debug=true;
 345  
 346          /// Both old .sql files and new install.xml are supported
 347          /// but we priorize install.xml (XMLDB) if present
 348              $status = false;
 349              if (file_exists($CFG->dirroot . '/backup/db/install.xml')) {
 350                  $status = install_from_xmldb_file($CFG->dirroot . '/backup/db/install.xml'); //New method
 351              } else if (file_exists($CFG->dirroot . '/backup/db/' . $CFG->dbtype . '.sql')) {
 352                  $status = modify_database($CFG->dirroot . '/backup/db/' . $CFG->dbtype . '.sql'); //Old method
 353              }
 354  
 355              $db->debug = false;
 356              if ($status) {
 357                  if (set_config("backup_version", $backup_version) and set_config("backup_release", $backup_release)) {
 358                      notify(get_string("databasesuccess"), "green");
 359                      notify(get_string("databaseupgradebackups", "", $backup_version), "green");
 360                      print_continue($continueto);
 361                      print_footer('none');
 362                      exit;
 363                  } else {
 364                      error("Upgrade of backup system failed! (Could not update version in config table)");
 365                  }
 366              } else {
 367                  error("Backup tables could NOT be set up successfully!");
 368              }
 369          }
 370  
 371      /// Upgrading code starts here
 372          $oldupgrade = false;
 373          $newupgrade = false;
 374          if (is_readable($CFG->dirroot . '/backup/db/' . $CFG->dbtype . '.php')) {
 375              include_once($CFG->dirroot . '/backup/db/' . $CFG->dbtype . '.php');  // defines old upgrading function
 376              $oldupgrade = true;
 377          }
 378          if (is_readable($CFG->dirroot . '/backup/db/upgrade.php')) {
 379              include_once($CFG->dirroot . '/backup/db/upgrade.php');  // defines new upgrading function
 380              $newupgrade = true;
 381          }
 382  
 383          if ($backup_version > $CFG->backup_version) {       // Upgrade tables
 384              $strdatabaseupgrades = get_string("databaseupgrades");
 385              $navigation = array(array('name' => $strdatabaseupgrades, 'link' => null, 'type' => 'misc'));
 386              print_header($strdatabaseupgrades, $strdatabaseupgrades, build_navigation($navigation), '', upgrade_get_javascript());
 387  
 388              upgrade_log_start();
 389              print_heading('backup');
 390  
 391          /// Run de old and new upgrade functions for the module
 392              $oldupgrade_function = 'backup_upgrade';
 393              $newupgrade_function = 'xmldb_backup_upgrade';
 394  
 395          /// First, the old function if exists
 396              $oldupgrade_status = true;
 397              if ($oldupgrade && function_exists($oldupgrade_function)) {
 398                  $db->debug = true;
 399                  $oldupgrade_status = $oldupgrade_function($CFG->backup_version);
 400              } else if ($oldupgrade) {
 401                  notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
 402                          '/backup/db/' . $CFG->dbtype . '.php');
 403              }
 404  
 405          /// Then, the new function if exists and the old one was ok
 406              $newupgrade_status = true;
 407              if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
 408                  $db->debug = true;
 409                  $newupgrade_status = $newupgrade_function($CFG->backup_version);
 410              } else if ($newupgrade) {
 411                  notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
 412                          '/backup/db/upgrade.php');
 413              }
 414  
 415              $db->debug=false;
 416          /// Now analyze upgrade results
 417              if ($oldupgrade_status && $newupgrade_status) {    // No upgrading failed
 418                  if (set_config("backup_version", $backup_version) and set_config("backup_release", $backup_release)) {
 419                      notify(get_string("databasesuccess"), "green");
 420                      notify(get_string("databaseupgradebackups", "", $backup_version), "green");
 421                      print_continue($continueto);
 422                      print_footer('none');
 423                      exit;
 424                  } else {
 425                      error("Upgrade of backup system failed! (Could not update version in config table)");
 426                  }
 427              } else {
 428                  error("Upgrade failed!  See backup/version.php");
 429              }
 430  
 431          } else if ($backup_version < $CFG->backup_version) {
 432              upgrade_log_start();
 433              notify("WARNING!!!  The code you are using is OLDER than the version that made these databases!");
 434          }
 435          upgrade_log_finish();
 436      }
 437  
 438  
 439      //This function is used to insert records in the backup_ids table
 440      //If the info field is greater than max_db_storage, then its info
 441      //is saved to filesystem
 442      function backup_putid ($backup_unique_code, $table, $old_id, $new_id, $info="") {
 443  
 444          global $CFG;
 445  
 446          $max_db_storage = 128;  //Max bytes to save to db, else save to file
 447  
 448          $status = true;
 449  
 450          //First delete to avoid PK duplicates
 451          $status = backup_delid($backup_unique_code, $table, $old_id);
 452  
 453          //Now, serialize info
 454          $info_ser = serialize($info);
 455  
 456          //Now, if the size of $info_ser > $max_db_storage, save it to filesystem and
 457          //insert a "infile" in the info field
 458  
 459          if (strlen($info_ser) > $max_db_storage) {
 460              //Calculate filename (in current_backup_dir, $backup_unique_code_$table_$old_id.info)
 461              $filename = $CFG->dataroot."/temp/backup/".$backup_unique_code."/".$backup_unique_code."_".$table."_".$old_id.".info";
 462              //Save data to file
 463              $status = backup_data2file($filename,$info_ser);
 464              //Set info_to save
 465              $info_to_save = "infile";
 466          } else {
 467              //Saving to db, addslashes
 468              $info_to_save = addslashes($info_ser);
 469          }
 470  
 471          //Now, insert the record
 472          if ($status) {
 473              //Build the record
 474              $rec = new object();
 475              $rec->backup_code = $backup_unique_code;
 476              $rec->table_name = $table;
 477              $rec->old_id = $old_id;
 478              $rec->new_id = ($new_id === null? 0 : $new_id);
 479              $rec->info = $info_to_save;
 480  
 481              if (!insert_record('backup_ids', $rec, false)) {
 482                  $status = false;
 483              }
 484          }
 485          return $status;
 486      }
 487  
 488      //This function is used to delete recods from the backup_ids table
 489      //If the info field is "infile" then the file is deleted too
 490      function backup_delid ($backup_unique_code, $table, $old_id) {
 491  
 492          global $CFG;
 493  
 494          $status = true;
 495  
 496          $status = execute_sql("DELETE FROM {$CFG->prefix}backup_ids
 497                                 WHERE backup_code = $backup_unique_code AND
 498                                       table_name = '$table' AND
 499                                       old_id = '$old_id'",false);
 500          return $status;
 501      }
 502  
 503      //This function is used to get a record from the backup_ids table
 504      //If the info field is "infile" then its info
 505      //is read from filesystem
 506      function backup_getid ($backup_unique_code, $table, $old_id) {
 507  
 508          global $CFG;
 509  
 510          $status = true;
 511          $status2 = true;
 512  
 513          $status = get_record ("backup_ids","backup_code",$backup_unique_code,
 514                                             "table_name",$table,
 515                                             "old_id", $old_id);
 516  
 517          //If info field = "infile", get file contents
 518          if (!empty($status->info) && $status->info == "infile") {
 519              $filename = $CFG->dataroot."/temp/backup/".$backup_unique_code."/".$backup_unique_code."_".$table."_".$old_id.".info";
 520              //Read data from file
 521              $status2 = backup_file2data($filename,$info);
 522              if ($status2) {
 523                  //unserialize data
 524                  $status->info = unserialize($info);
 525              } else {
 526                  $status = false;
 527              }
 528          } else {
 529              //Only if status (record exists)
 530              if (!empty($status->info)) {
 531                  if ($status->info === 'needed') { 
 532                      // TODO: ugly hack - fix before 1.9.1 
 533                      debugging('Incorrect string "needed" in $status->info, please fix the code (table:'.$table.'; old_id:'.$old_id.').', DEBUG_DEVELOPER);
 534                  } else {
 535                      ////First strip slashes
 536                      $temp = stripslashes($status->info);
 537                      //Now unserialize
 538                      $status->info = unserialize($temp);
 539                  }
 540              }
 541          }
 542  
 543          return $status;
 544      }
 545  
 546      //This function is used to add slashes (and decode from UTF-8 if needed)
 547      //It's used intensivelly when restoring modules and saving them in db
 548      function backup_todb ($data, $addslashes=true) {
 549          // MDL-10770
 550          if ($data === '$@NULL@$') {
 551              return null;
 552          } else {
 553              if ($addslashes) {
 554                  $data = addslashes($data);
 555              }
 556              return restore_decode_absolute_links($data);
 557          }
 558      }
 559  
 560      //This function is used to check that every necessary function to
 561      //backup/restore exists in the current php installation. Thanks to
 562      //gregb@crowncollege.edu by the idea.
 563      function backup_required_functions($justcheck=false) {
 564  
 565          if(!function_exists('utf8_encode')) {
 566              if (empty($justcheck)) {
 567                  error('You need to add XML support to your PHP installation');
 568              } else {
 569                  return false;
 570              }
 571          }
 572  
 573          return true;
 574      }
 575  
 576      //This function send n white characters to the browser and flush the
 577      //output buffer. Used to avoid browser timeouts and to show the progress.
 578      function backup_flush($n=0,$time=false) {
 579          if (defined('RESTORE_SILENTLY_NOFLUSH')) {
 580              return;
 581          }
 582          if ($time) {
 583              $ti = strftime("%X",time());
 584          } else {
 585              $ti = "";
 586          }
 587          echo str_repeat(" ", $n) . $ti . "\n";
 588          flush();
 589      }
 590  
 591      //This function creates the filename and write data to it
 592      //returning status as result
 593      function backup_data2file ($file,&$data) {
 594  
 595          $status = true;
 596          $status2 = true;
 597  
 598          $f = fopen($file,"w");
 599          $status = fwrite($f,$data);
 600          $status2 = fclose($f);
 601  
 602          return ($status && $status2);
 603      }
 604  
 605      //This function read the filename and read data from it
 606      function backup_file2data ($file,&$data) {
 607  
 608          $status = true;
 609          $status2 = true;
 610  
 611          $f = fopen($file,"r");
 612          $data = fread ($f,filesize($file));
 613          $status2 = fclose($f);
 614  
 615          return ($status && $status2);
 616      }
 617  
 618      /** this function will restore an entire backup.zip into the specified course
 619       * using standard moodle backup/restore functions, but silently.
 620       * @param string $pathtofile the absolute path to the backup file.
 621       * @param int $destinationcourse the course id to restore to.
 622       * @param boolean $emptyfirst whether to delete all coursedata first.
 623       * @param boolean $userdata whether to include any userdata that may be in the backup file.
 624       * @param array $preferences optional, 0 will be used.  Can contain:
 625       *   metacourse
 626       *   logs
 627       *   course_files
 628       *   messages
 629       */
 630      function import_backup_file_silently($pathtofile,$destinationcourse,$emptyfirst=false,$userdata=false, $preferences=array()) {
 631          global $CFG,$SESSION,$USER; // is there such a thing on cron? I guess so..
 632          global $restore; // ick
 633          if (empty($USER)) {
 634              $USER = get_admin();
 635              $USER->admin = 1; // not sure why, but this doesn't get set
 636          }
 637  
 638          define('RESTORE_SILENTLY',true); // don't output all the stuff to us.
 639  
 640          $debuginfo = 'import_backup_file_silently: ';
 641          $cleanupafter = false;
 642          $errorstr = ''; // passed by reference to restore_precheck to get errors from.
 643  
 644          if (!$course = get_record('course','id',$destinationcourse)) {
 645              mtrace($debuginfo.'Course with id $destinationcourse was not a valid course!');
 646              return false;
 647          }
 648  
 649          // first check we have a valid file.
 650          if (!file_exists($pathtofile) || !is_readable($pathtofile)) {
 651              mtrace($debuginfo.'File '.$pathtofile.' either didn\'t exist or wasn\'t readable');
 652              return false;
 653          }
 654  
 655          // now make sure it's a zip file
 656          require_once($CFG->dirroot.'/lib/filelib.php');
 657          $filename = substr($pathtofile,strrpos($pathtofile,'/')+1);
 658          $mimetype = mimeinfo("type", $filename);
 659          if ($mimetype != 'application/zip') {
 660              mtrace($debuginfo.'File '.$pathtofile.' was of wrong mimetype ('.$mimetype.')' );
 661              return false;
 662          }
 663  
 664          // restore_precheck wants this within dataroot, so lets put it there if it's not already..
 665          if (strstr($pathtofile,$CFG->dataroot) === false) {
 666              // first try and actually move it..
 667              if (!check_dir_exists($CFG->dataroot.'/temp/backup/',true)) {
 668                  mtrace($debuginfo.'File '.$pathtofile.' outside of dataroot and couldn\'t move it! ');
 669                  return false;
 670              }
 671              if (!copy($pathtofile,$CFG->dataroot.'/temp/backup/'.$filename)) {
 672                  mtrace($debuginfo.'File '.$pathtofile.' outside of dataroot and couldn\'t move it! ');
 673                  return false;
 674              } else {
 675                  $pathtofile = 'temp/backup/'.$filename;
 676                  $cleanupafter = true;
 677              }
 678          } else {
 679              // it is within dataroot, so take it off the path for restore_precheck.
 680              $pathtofile = substr($pathtofile,strlen($CFG->dataroot.'/'));
 681          }
 682  
 683          if (!backup_required_functions()) {
 684              mtrace($debuginfo.'Required function check failed (see backup_required_functions)');
 685              return false;
 686          }
 687  
 688          @ini_set("max_execution_time","3000");
 689          raise_memory_limit("192M");
 690  
 691          if (!$backup_unique_code = restore_precheck($destinationcourse,$pathtofile,$errorstr,true)) {
 692              mtrace($debuginfo.'Failed restore_precheck (error was '.$errorstr.')');
 693              return false;
 694          }
 695  
 696          $SESSION->restore = new StdClass;
 697  
 698          // add on some extra stuff we need...
 699          $SESSION->restore->metacourse   = $restore->metacourse = (isset($preferences['restore_metacourse']) ? $preferences['restore_metacourse'] : 0);
 700          $SESSION->restore->restoreto    = $restore->restoreto = 1;
 701          $SESSION->restore->users        = $restore->users = $userdata;
 702          $SESSION->restore->logs         = $restore->logs = (isset($preferences['restore_logs']) ? $preferences['restore_logs'] : 0);
 703          $SESSION->restore->user_files   = $restore->user_files = $userdata;
 704          $SESSION->restore->messages     = $restore->messages = (isset($preferences['restore_messages']) ? $preferences['restore_messages'] : 0);
 705          $SESSION->restore->course_id    = $restore->course_id = $destinationcourse;
 706          $SESSION->restore->restoreto    = 1;
 707          $SESSION->restore->course_id    = $destinationcourse;
 708          $SESSION->restore->deleting     = $emptyfirst;
 709          $SESSION->restore->restore_course_files = $restore->course_files = (isset($preferences['restore_course_files']) ? $preferences['restore_course_files'] : 0);
 710          $SESSION->restore->backup_version = $SESSION->info->backup_backup_version;
 711          $SESSION->restore->course_startdateoffset = $course->startdate - $SESSION->course_header->course_startdate;
 712  
 713          restore_setup_for_check($SESSION->restore,$backup_unique_code);
 714  
 715          // maybe we need users (defaults to 2 in restore_setup_for_check)
 716          if (!empty($userdata)) {
 717              $SESSION->restore->users = 1;
 718          }
 719  
 720          // we also need modules...
 721          if ($allmods = get_records("modules")) {
 722              foreach ($allmods as $mod) {
 723                  $modname = $mod->name;
 724                  //Now check that we have that module info in the backup file
 725                  if (isset($SESSION->info->mods[$modname]) && $SESSION->info->mods[$modname]->backup == "true") {
 726                      $SESSION->restore->mods[$modname]->restore = true;
 727                      $SESSION->restore->mods[$modname]->userinfo = $userdata;
 728                  }
 729                  else {
 730                      // avoid warnings
 731                      $SESSION->restore->mods[$modname]->restore = false;
 732                      $SESSION->restore->mods[$modname]->userinfo = false;
 733                  }
 734              }
 735          }
 736          $restore = clone($SESSION->restore);
 737          if (!restore_execute($SESSION->restore,$SESSION->info,$SESSION->course_header,$errorstr)) {
 738              mtrace($debuginfo.'Failed restore_execute (error was '.$errorstr.')');
 739              return false;
 740          }
 741          return true;
 742      }
 743  
 744      /**
 745      * Function to backup an entire course silently and create a zipfile.
 746      *
 747      * @param int $courseid the id of the course
 748      * @param array $prefs see {@link backup_generate_preferences_artificially}
 749      */
 750      function backup_course_silently($courseid, $prefs, &$errorstring) {
 751          global $CFG, $preferences; // global preferences here because something else wants it :(
 752          define('BACKUP_SILENTLY', 1);
 753          if (!$course = get_record('course', 'id', $courseid)) {
 754              debugging("Couldn't find course with id $courseid in backup_course_silently");
 755              return false;
 756          }
 757          $preferences = backup_generate_preferences_artificially($course, $prefs);
 758          if (backup_execute($preferences, $errorstring)) {
 759              return $CFG->dataroot . '/' . $course->id . '/backupdata/' . $preferences->backup_name;
 760          }
 761          else {
 762              return false;
 763          }
 764      }
 765  
 766      /**
 767      * Function to generate the $preferences variable that
 768      * backup uses.  This will back up all modules and instances in a course.
 769      *
 770      * @param object $course course object
 771      * @param array $prefs can contain:
 772              backup_metacourse
 773              backup_users
 774              backup_logs
 775              backup_user_files
 776              backup_course_files
 777              backup_site_files
 778              backup_messages
 779      * and if not provided, they will not be included.
 780      */
 781  
 782      function backup_generate_preferences_artificially($course, $prefs) {
 783          global $CFG;
 784          $preferences = new StdClass;
 785          $preferences->backup_unique_code = time();
 786          $preferences->backup_name = backup_get_zipfile_name($course, $preferences->backup_unique_code);
 787          $count = 0;
 788  
 789          if ($allmods = get_records("modules") ) {
 790              foreach ($allmods as $mod) {
 791                  $modname = $mod->name;
 792                  $modfile = "$CFG->dirroot/mod/$modname/backuplib.php";
 793                  $modbackup = $modname."_backup_mods";
 794                  $modbackupone = $modname."_backup_one_mod";
 795                  $modcheckbackup = $modname."_check_backup_mods";
 796                  if (!file_exists($modfile)) {
 797                      continue;
 798                  }
 799                  include_once($modfile);
 800                  if (!function_exists($modbackup) || !function_exists($modcheckbackup)) {
 801                      continue;
 802                  }
 803                  $var = "exists_".$modname;
 804                  $preferences->$var = true;
 805                  $count++;
 806                  // check that there are instances and we can back them up individually
 807                  if (!count_records('course_modules','course',$course->id,'module',$mod->id) || !function_exists($modbackupone)) {
 808                      continue;
 809                  }
 810                  $var = 'exists_one_'.$modname;
 811                  $preferences->$var = true;
 812                  $varname = $modname.'_instances';
 813                  $preferences->$varname = get_all_instances_in_course($modname, $course, NULL, true);
 814                  foreach ($preferences->$varname as $instance) {
 815                      $preferences->mods[$modname]->instances[$instance->id]->name = $instance->name;
 816                      $var = 'backup_'.$modname.'_instance_'.$instance->id;
 817                      $preferences->$var = true;
 818                      $preferences->mods[$modname]->instances[$instance->id]->backup = true;
 819                      $var = 'backup_user_info_'.$modname.'_instance_'.$instance->id;
 820                      $preferences->$var = true;
 821                      $preferences->mods[$modname]->instances[$instance->id]->userinfo = true;
 822                      $var = 'backup_'.$modname.'_instances';
 823                      $preferences->$var = 1; // we need this later to determine what to display in modcheckbackup.
 824                  }
 825  
 826                  //Check data
 827                  //Check module info
 828                  $preferences->mods[$modname]->name = $modname;
 829  
 830                  $var = "backup_".$modname;
 831                  $preferences->$var = true;
 832                  $preferences->mods[$modname]->backup = true;
 833  
 834                  //Check include user info
 835                  $var = "backup_user_info_".$modname;
 836                  $preferences->$var = true;
 837                  $preferences->mods[$modname]->userinfo = true;
 838  
 839              }
 840          }
 841  
 842          //Check other parameters
 843          $preferences->backup_metacourse = (isset($prefs['backup_metacourse']) ? $prefs['backup_metacourse'] : 0);
 844          $preferences->backup_users = (isset($prefs['backup_users']) ? $prefs['backup_users'] : 0);
 845          $preferences->backup_logs = (isset($prefs['backup_logs']) ? $prefs['backup_logs'] : 0);
 846          $preferences->backup_user_files = (isset($prefs['backup_user_files']) ? $prefs['backup_user_files'] : 0);
 847          $preferences->backup_course_files = (isset($prefs['backup_course_files']) ? $prefs['backup_course_files'] : 0);
 848          $preferences->backup_site_files = (isset($prefs['backup_site_files']) ? $prefs['backup_site_files'] : 0);
 849          $preferences->backup_messages = (isset($prefs['backup_messages']) ? $prefs['backup_messages'] : 0);
 850          $preferences->backup_gradebook_history = (isset($prefs['backup_gradebook_history']) ? $prefs['backup_gradebook_history'] : 0);
 851          $preferences->backup_blogs = (isset($prefs['backup_blogs']) ? $prefs['backup_blogs'] : 0);
 852          $preferences->backup_course = $course->id;
 853          backup_add_static_preferences($preferences);
 854          return $preferences;
 855      }
 856  
 857  
 858  ?>


Generated: Wed Jan 14 11:33:29 2009 Cross-referenced by PHPXref 0.7