[ PHPXref.com ] [ Generated: Sun Jul 20 18:27:23 2008 ] [ Legal Case 0.6.4b ]
[ Index ]     [ Variables ]     [ Functions ]     [ Classes ]     [ Constants ]     [ Statistics ]

title

Body

[close]

/ -> import_db.php (source)

   1  <?php
   2  
   3  /*
   4      This file is part of the Legal Case Management System (LCM).
   5      (C) 2004-2005 Free Software Foundation, Inc.
   6  
   7      This program is free software; you can redistribute it and/or modify it
   8      under the terms of the GNU General Public License as published by the
   9      Free Software Foundation; either version 2 of the License, or (at your
  10      option) any later version.
  11  
  12      This program is distributed in the hope that it will be useful, but
  13      WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  14      or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15      for more details.
  16  
  17      You should have received a copy of the GNU General Public License along
  18      with this program; if not, write to the Free Software Foundation, Inc.,
  19      59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
  20  
  21      $Id: import_db.php,v 1.10.2.10 2005/11/14 11:11:38 mlutfy Exp $
  22  */
  23  
  24  include ('inc/inc.php');
  25  include_lcm('inc_filters');
  26  include_lcm('inc_conditions');
  27  
  28  define('DIR_BACKUPS', (isset($_SERVER['LcmDataDir']) ? $_SERVER['LcmDataDir'] : addslashes(getcwd()) . '/inc/data'));
  29  define('DIR_BACKUPS_PREFIX', DIR_BACKUPS . '/db-');
  30  
  31  define('DATA_EXT_NAME', '.csv');
  32  define('DATA_EXT_LEN', strlen(lcm_utf8_decode(DATA_EXT_NAME)));
  33  
  34  if (! isset($_SESSION['errors']))
  35      $_SESSION['errors'] = array();
  36  
  37  $tabs = array(    array('name' => _T('archives_tab_all_cases'), 'url' => 'archive.php'),
  38          array('name' => _T('archives_tab_export'), 'url' => 'export_db.php'),
  39          array('name' => _T('archives_tab_import'), 'url' => 'import_db.php')
  40      );
  41  
  42  function show_import_form() {
  43      lcm_page_start(_T('title_archives'), '', '', 'archives_import');
  44  
  45      global $tabs;
  46      show_tabs_links($tabs, 2);
  47      lcm_bubble('archive_restore');
  48  
  49      // Show the errors (if any)
  50      echo show_all_errors($_SESSION['errors']);
  51  
  52      // Upload backup form
  53      echo '<form enctype="multipart/form-data" action="import_db.php" method="post">' . "\n";
  54      echo '<input type="hidden" name="action" value="upload_file" />' . "\n";
  55      echo '<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />' . "\n";
  56  
  57      echo "<fieldset class='info_box'>\n";
  58      show_page_subtitle(_T('archives_subtitle_upload'), 'archives_import', 'newrestore');
  59  
  60      echo '<p class="normal_text">' . _T('archives_info_how_to_upload') . "</p>\n";
  61      echo '<p class="normal_text">' . _Ti('file_input_name');
  62      echo '<input type="file" name="filename" size="40" value="" /> ';
  63      echo '<input type="submit" name="submit" id="btn_upload" value="' . _T('button_validate') . '" class="search_form_btn" />';
  64      echo "</p>\n";
  65  
  66      echo "</fieldset>\n";
  67      echo "</form>\n";
  68  
  69      // Restore backup form
  70      echo '<form action="import_db.php" method="post">' . "\n";
  71      echo '<input type="hidden" name="action" value="import" />' . "\n";
  72  
  73      echo "<fieldset class='info_box'>\n";
  74      show_page_subtitle(_T('archives_subtitle_restore'), 'archives_import', 'delrestore');
  75  
  76      echo "<strong>" . _Ti('archives_input_select_backup') . "</strong><br />";
  77      echo "<select name='file' class='sel_frm'>\n";
  78  
  79      $storage = opendir(DIR_BACKUPS);
  80      while (($file = readdir($storage))) {
  81          if (is_dir(DIR_BACKUPS . '/' . $file) && (strpos($file,'db-')===0))
  82              echo "\t\t<option value='" . substr($file,3) . "'>" . substr($file,3) . "</option>\n";
  83      }
  84      echo "</select>\n";
  85      
  86      // Select restore type
  87      echo "<p class='normal_text'>\n";
  88      echo "<input type='radio' name='restore_type' value='clean' id='r1' /><label for='r1'>&nbsp;<strong>" . _T('archives_input_option_restore') .  "</strong></label><br />" . _T('archives_info_option_restore') . "<br /><br />\n";
  89      
  90      // [ML] This is confusing as hell. I understand the aim from DB point of view
  91      // but I don't understand the aim from the admin's point of view.
  92      // echo "<input type='radio' name='restore_type' value='replace' id='r2' /><label for='r2'>&nbsp;<strong>Replace (experimental!)</strong></label><br /> Imported backup data will replace the existing. This is usefull to undo the changes made in the database since last backup, without losing the new information. Warning: This operation could break database integrity, especially if importing data between different LCM installations.<br /><br />\n";
  93  
  94      echo "<input type='radio' name='restore_type' value='ignore' id='r3' /><label for='r3'>&nbsp;<strong>" . _T('archives_input_option_sync') . " (experimental!)</strong></label><br /> Only backup data NOT existing in the database will be imported. This is usefull to import data lost since last backup, without changing the existing information. Warning: This operation could break database integrity, especially if importing data between different LCM installations.<br /><br />\n"; // TRAD
  95  
  96      echo "<button type='submit' class='simple_form_btn'>" . _T('button_validate') . "</button>\n";
  97      echo "</p>\n";
  98      echo "</fieldset\n>";
  99      echo "</form>\n";
 100  
 101      lcm_page_end();
 102      $_SESSION['errors'] = array();
 103  }
 104  
 105  function import_database($input_filename) {
 106      global $tabs;
 107  
 108      $input_filename = clean_input($input_filename);
 109      $root = addslashes(getcwd());
 110      $dir = DIR_BACKUPS_PREFIX . $input_filename;
 111  
 112      if (file_exists($dir)) {
 113          if ($_POST['conf']!=='yes') {
 114              // Print confirmation form
 115              lcm_page_start(_T('title_archives'), '', '', 'archives_import');
 116              show_tabs_links($tabs,2,true);
 117  
 118              echo "<fieldset class='info_box'>\n";
 119              show_page_subtitle(_T('generic_subtitle_warning'), 'archives_import');
 120  
 121              echo "<p class='normal_text'><img src='images/jimmac/icon_warning.gif' alt='' "
 122                  . "align='right' height='48' width='48' />" 
 123                  . _T('archives_info_restore_will_delete')
 124                  . "</p>\n";
 125  
 126              echo "<form action='import_db.php' method='post'>\n";
 127              echo '<input type="hidden" name="action" value="import" />' . "\n";
 128  
 129              echo "<button type='submit' class='simple_form_btn' name='conf' value='yes'>" . _T('info_yes') . "</button>\n";
 130              echo "<button type='submit' class='simple_form_btn' name='conf' value='no'>" . _T('info_no') . "</button>\n";
 131              echo "<input type='hidden' name='file' value='$input_filename' />\n";
 132              echo "<input type='hidden' name='restore_type' value='" . $_POST['restore_type'] . "' />\n";
 133              echo "</form>";
 134              echo "</fieldset\n>";
 135              lcm_page_end();
 136              return;
 137          }
 138      }
 139  
 140      // Get saved database version
 141      if (! ($fh = fopen("$dir/db-version",'r')))
 142          lcm_panic("System error: Could not open file '$dir/db-version");
 143  
 144      $backup_db_version = intval(fread($fh,10));
 145      fclose($fh);
 146  
 147      // For debugging - use another database
 148      //lcm_query("use lcm_new");
 149      
 150      // Recreate tables
 151      if ( ($_POST['restore_type'] == 'clean') || ($backup_db_version < read_meta('lcm_db_version')) ) {
 152          // Open backup dir
 153          if (! ($dh = opendir("$dir/")))
 154              lcm_panic("System error: Could not open directory '$dir'");
 155  
 156          while (($file = readdir($dh))) {
 157              // Get table name
 158              $table = substr($file,0,-10);
 159  
 160              // Add path to filename
 161              $file = "$dir/$file";
 162              if (strlen($file) > 10) {
 163                  if (is_file($file) && (substr($file,-10) === ".structure")
 164                      && is_file("$dir/$table" . DATA_EXT_NAME)) 
 165                  {
 166                      // Clear the table
 167                      $q = "DROP TABLE IF EXISTS $table";
 168                      $result = lcm_query($q);
 169  
 170                      // Create table
 171                      $fh = fopen($file,'r');
 172                      $q = fread($fh,filesize($file));
 173                      fclose($fh);
 174                      $result = lcm_query_create_table($q, true);
 175                  }
 176              }
 177          }
 178  
 179          closedir($dh);
 180  
 181          // Update lcm_db_version
 182          // [ML] This is rather useless because they will be overwritten when the
 183          // values are loaded (LOAD FILE), but I leave it just in case there are
 184          // obscur bugs (altough this will most likely generate strange bugs..)
 185          write_meta('lcm_db_version', $backup_db_version);
 186  
 187          if (! preg_match('/^MySQL (4\.0|3\.)/', lcm_sql_server_info()))
 188              write_meta('db_utf8', 'yes');
 189  
 190          write_metas();
 191      }    // Old backup version
 192      else if ($backup_db_version > read_meta('lcm_db_version')) {
 193          // Backup version newer than installed db version
 194          lcm_page_start(_T('title_archives'), '', '', 'archives_import');
 195          
 196          // Show tabs
 197          show_tabs_links($tabs,2,true);
 198  
 199          // Show tab header
 200          echo "Version mismatch!\n"; // TRAD
 201  
 202          echo "<fieldset class='info_box'>\n";
 203          echo "Backup database version is newer than the installed database."; // TRAD
 204          echo "</fieldset\n>";
 205          lcm_page_end();
 206          return;
 207      }    // Backup version newer than installed db version
 208      else {
 209          // Backup and current db versions are equal
 210      }
 211      
 212      //
 213      // Import data into database tables\
 214      //
 215      
 216      // Change backup dir permissions, so MySQL could read from it.
 217      chmod($dir,0755);
 218  
 219      // Open backup dir
 220      if (! ($dh = opendir("$dir/")))
 221          lcm_panic("System error: Could not open directory '$dir'");
 222  
 223      while (($file = readdir($dh))) {
 224          // Get table name
 225          $table = substr($file,0,- DATA_EXT_LEN);
 226          // Add path to filename
 227          $file = "$dir/$file";
 228          if (strlen($file) > 5) { // [ML] why?
 229              if (is_file($file) && (substr($file, - DATA_EXT_LEN) === DATA_EXT_NAME)) {
 230                  // If restore_type='clean', clear the table
 231                  if ($_POST['restore_type'] == 'clean')
 232                      lcm_query("TRUNCATE TABLE $table");
 233                  
 234                  $q = "LOAD DATA INFILE '$file' ";
 235                  $q .= (($_POST['restore_type'] == 'replace') ? 'REPLACE' : 'IGNORE');
 236                  $q .= "    INTO TABLE $table
 237                      FIELDS TERMINATED BY ','
 238                          OPTIONALLY ENCLOSED BY '\"'
 239                          ESCAPED BY '\\\\'
 240                      LINES TERMINATED BY '\r\n'";
 241                  
 242                  $result = lcm_query($q);
 243              }
 244          }
 245      }
 246  
 247      closedir($dh);
 248  
 249      // Change backup dir permissions back
 250      chmod($dir, 0700);
 251      
 252      // Update lcm_db_version since we have overwritten lcm_meta
 253      write_meta('lcm_db_version', $backup_db_version);
 254  
 255      if ($_REQUEST['restore_type'] == 'clean')
 256          if (! preg_match('/^MySQL (4\.0|3\.)/', lcm_sql_server_info()))
 257              write_meta('db_utf8', 'yes');
 258  
 259      write_metas();
 260  
 261      lcm_page_start(_T('title_archives'), '', '', 'archives_import'); // FIXME?
 262      show_tabs_links($tabs,2,true);
 263  
 264      echo '<div class="sys_msg_box">' . "\n";
 265      show_page_subtitle("Import finished", 'archives_import'); // FIXME TRAD? 
 266  
 267      echo "Backup '$input_filename' was successfully imported into database."; // TRAD
 268      echo "</div\n>";
 269      lcm_page_end();
 270  
 271  }
 272  
 273  function upload_backup_file() {
 274      // File name and extention
 275      $fname = "";
 276      $fext  = "";
 277  
 278      // Clear all previous errors
 279      $_SESSION['errors'] = array();
 280  
 281      if (! is_uploaded_file($_FILES['filename']['tmp_name'])) {
 282          // FIXME: error message
 283          $_SESSION['errors']['upload_file'] = '1 - not a valid file'; // TRAD
 284          return;
 285      }
 286  
 287      if (! ($_FILES['filename']['size'] > 0)) {
 288          // FIXME: error message
 289          $_SESSION['errors']['upload_file'] = 'size is zero'; // TRAD
 290          return;
 291      }
 292  
 293      // File should be: name.tar or name.tar.gz or name.tgz
 294      // name can be pretty much anything, since it will be rawurlencoded()
 295      // if it is prefixed with "db-", it will be removed and later added again
 296      if (preg_match("/^(db-)?(.+)\.(tar(\.gz)?|tgz)$/", $_FILES['filename']['name'], $regs)) {
 297          $fname = rawurlencode($regs[2]);
 298          $fext  = $regs[3];
 299      } else {
 300          // FIXME: error
 301          $_SESSION['errors']['upload_file'] = 'name not accepted'; // TRAD
 302          return;
 303      }
 304  
 305      $cpt = 0;
 306      while (file_exists(DIR_BACKUPS_PREFIX . $fname . ($cpt ? "-" . $cpt : '') . "." . $fext))
 307          $cpt++;
 308  
 309      $fname_full = DIR_BACKUPS_PREFIX . $fname . ($cpt ? "-" . $cpt : '') . "." . $fext;
 310  
 311      if (! move_uploaded_file($_FILES['filename']['tmp_name'], $fname_full)) {
 312          // FIXME: error message
 313          $_SESSION['errors']['upload_file'] = 'move_uploaded_file freaked out'; // TRAD
 314          return;
 315      }
 316  
 317      if (is_file($fname_full)) {
 318          // unpackage
 319          @include("Archive/Tar.php");
 320          $tar_worked = false;
 321  
 322          if (class_exists("Archive_Tar")) {
 323              $tar_worked = true;
 324              $tar_object = new Archive_Tar($fname_full);
 325              $tar_object->setErrorHandling(PEAR_ERROR_PRINT);
 326  
 327              // XXX is this safe to do this here? What if file exists?
 328              // FIXME: check extractList() to modify dest path
 329              $tar_object->extract();
 330          } else {
 331              $_SESSION['errors']['upload_file'] = "Archive::Tar not installed"; // TRAD
 332              return;
 333          }
 334      } else {
 335          lcm_panic("This should not happen...");
 336      }
 337  }
 338  
 339  //
 340  // Main
 341  //
 342  
 343  global $author_session;
 344  
 345  // Restrict page to administrators
 346  if ($author_session['status'] != 'admin') {
 347      lcm_page_start(_T('title_archives'), '', '', 'archives_import');
 348      echo '<p class="normal_text">' . _T('warning_forbidden_not_admin') . "</p>\n";
 349      lcm_page_end();
 350      exit;
 351  }
 352  
 353  switch($_REQUEST['action']) {
 354      case 'upload_file':
 355          upload_backup_file($_REQUEST['file']);
 356          show_import_form();
 357          break;
 358      case 'import':
 359          if ($_REQUEST['file']) {
 360              import_database($_REQUEST['file']);
 361          } else {
 362              // FIXME: show error message
 363              show_import_form();
 364          }
 365          break;
 366      default:
 367          show_import_form();
 368  }
 369  
 370  
 371  ?>


[ Powered by PHPXref - Served by Debian GNU/Linux ]