[ Index ]

PHP Cross Reference of Mambo 4.6.5

[ Variables ]     [ Functions ]     [ Classes ]     [ Constants ]     [ Statistics ]

title

Body

[close]

/administrator/components/com_mostlydbadmin/ -> admin.mostlydbadmin.php (source)

   1  <?php
   2  /**
   3  * @package Mambo
   4  * @author Mambo Foundation Inc see README.php
   5  * @copyright (C) 2000 - 2009 Mambo Foundation Inc.
   6  * See COPYRIGHT.php for copyright notices and details.
   7  * @license GNU/GPL Version 2, see LICENSE.php
   8  *
   9  * Redistributions of files must retain the above copyright notice.
  10  *
  11  * Mambo is free software; you can redistribute it and/or
  12  * modify it under the terms of the GNU General Public License
  13  * as published by the Free Software Foundation; version 2 of the License.
  14  */
  15  
  16  /** ensure this file is being included by a parent file */
  17  defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
  18  
  19  // ensure user is coming from the admin side and has access to this function
  20  if (!($my->usertype=='Super Administrator') && $adminside>0) {
  21      mosRedirect( 'index2.php', T_('You are not authorized to view this resource.') );
  22  }
  23  
  24  require_once( $mainframe->getPath( 'admin_html' ) );
  25  require_once( "$mosConfig_absolute_path/administrator/includes/pcl/pclzip.lib.php" );
  26  
  27  $task    = mosGetParam( $_REQUEST, "task", "" );
  28  $file    = mosGetParam( $_POST, "file", null );
  29  $upfile    = mosGetParam($_FILES,"upfile",null);
  30  $tables = mosGetParam( $_POST, "tables", null );
  31  $OutType = mosGetParam( $_POST, "OutType", null );
  32  $OutDest = mosGetParam( $_POST, "OutDest", null );
  33  $toBackUp = mosGetParam( $_POST, "toBackUp", null );
  34  
  35  switch ($task) {
  36      case "dbBackup":
  37          dbBackup( $option);
  38          break;
  39  
  40      case "doBackup":
  41          doBackup( $tables,$OutType,$OutDest,$toBackUp,$_SERVER['HTTP_USER_AGENT'], $local_backup_path);
  42          break;
  43  
  44      case "dbRestore":
  45          dbRestore( $local_backup_path);
  46          break;
  47  
  48      case "doRestore":
  49          doRestore( $file,$upfile,$local_backup_path);
  50          break;
  51  
  52      case "xquery":
  53          xquery( $option );
  54          break;
  55  }
  56  
  57  
  58  function dbBackup( $p_option ) {
  59      global $database;
  60  
  61      // @RawSQLUse, trivial_implementation
  62      $database->setQuery( "SHOW tables" );
  63      $tables = $database->loadResultArray();
  64      $tables2 = array( mosHTML::makeOption( 'all', T_('All Mambo Tables') ) );
  65      foreach ($tables as $table) {
  66          $tables2[] = mosHTML::makeOption( $table );
  67      }
  68  
  69      $tablelist = mosHTML::selectList( $tables2, 'tables[]', 'class="inputbox" size="5" multiple="multiple"',
  70      'value', 'text', 'all' );
  71  
  72      HTML_dbadmin::backupIntro( $tablelist, $p_option );
  73  }
  74  
  75  function doBackup( $tables, $OutType, $OutDest, $toBackUp, $UserAgent, $local_backup_path) {
  76      global $database;
  77      global $mosConfig_db, $mosConfig_sitename, $version,$option,$task;
  78  
  79      if (!$tables[0])
  80      {
  81          HTML_dbadmin::showDbAdminMessage(T_('Error! No database table(s) specified. Please select at least one table and re-try.</p>'), T_('DB Admin'),$option,$task);
  82          return;
  83      }
  84  
  85      /* Need to know what browser the user has to accomodate nonstandard headers */
  86  
  87      if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $UserAgent)) {
  88          $UserBrowser = "Opera";
  89      }
  90      elseif (ereg('MSIE ([0-9].[0-9]{1,2})', $UserAgent)) {
  91          $UserBrowser = "IE";
  92      } else {
  93          $UserBrowser = '';
  94      }
  95  
  96      /* Determine the mime type and file extension for the output file */
  97  
  98      if ($OutType == "bzip") {
  99          $filename = $mosConfig_db . "_" . date("YmdHis") . ".bz2";
 100          $mime_type = 'application/x-bzip';
 101      } elseif ($OutType == "gzip") {
 102          $filename = $mosConfig_db . "_" . date("YmdHis") . ".sql.gz";
 103          $mime_type = 'application/x-gzip';
 104      } elseif ($OutType == "zip") {
 105          $filename = $mosConfig_db . "_" . date("YmdHis") . ".zip";
 106          $mime_type = 'application/x-zip';
 107      } elseif ($OutType == "html") {
 108          $filename = $mosConfig_db . "_" . date("YmdHis") . ".html";
 109          $mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
 110      } else {
 111          $filename = $mosConfig_db . "_" . date("YmdHis") . ".sql";
 112          $mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
 113      };
 114  
 115      /* Store all the tables we want to back-up in variable $tables[] */
 116  
 117      if ($tables[0] == "all") {
 118          array_pop($tables);
 119          // @RawSQLUse, trivial_implementation
 120          $database->setQuery("SHOW tables");
 121          $database->query();
 122          $tables = array_merge($tables, $database->loadResultArray());
 123      }
 124  
 125      /* Store the "Create Tables" SQL in variable $CreateTable[$tblval] */
 126      if ($toBackUp!="data")
 127      {
 128          foreach ($tables as $tblval)
 129          {
 130              // @RawSQLUse, trivial_implementation
 131              $database->setQuery("SHOW CREATE table $tblval");
 132              $database->query();
 133              $CreateTable[$tblval] = $database->loadResultArray(1);
 134          }
 135      }
 136  
 137      /* Store all the FIELD TYPES being backed-up (text fields need to be delimited) in variable $FieldType*/
 138      if ($toBackUp!="structure")
 139      {
 140          foreach ($tables as $tblval)
 141          {
 142              // @RawSQLUse, trivial_implementation
 143              $database->setQuery("SHOW FIELDS FROM $tblval");
 144              $database->query();
 145              $fields = $database->loadObjectList();
 146              foreach($fields as $field)
 147              {
 148                  $FieldType[$tblval][$field->Field] = preg_replace("/[(0-9)]/",'', $field->Type);
 149              }
 150          }
 151      }
 152  
 153      /* Build the fancy header on the dump file */
 154      $OutBuffer = "";
 155      if ($OutType == 'html') {
 156      } else {
 157          $OutBuffer .= "#\n";
 158          $OutBuffer .= "# Mambo MySQL-Dump\n";
 159          $OutBuffer .= "# http://www.mambo-foundation.org\n";
 160          $OutBuffer .= "#\n";
 161          $OutBuffer .= "# Host: $mosConfig_sitename\n";
 162          $OutBuffer .= "# Generation Time: " . date("M j, Y \a\\t H:i") . "\n";
 163          $OutBuffer .= "# Server version: " . $database->getVersion() . "\n";
 164          $OutBuffer .= "# PHP Version: " . phpversion() . "\n";
 165          $OutBuffer .= "# Database : `" . $mosConfig_db . "`\n# --------------------------------------------------------\n";
 166      }
 167  
 168      /* Okay, here's the meat & potatoes */
 169      foreach ($tables as $tblval) {
 170          if ($toBackUp != "data") {
 171              if ($OutType == 'html') {
 172              } else {
 173                  $OutBuffer .= "#\n# Table structure for table `$tblval`\n";
 174                  $OutBuffer .= "#\nDROP table IF EXISTS $tblval;\n";
 175                  $OutBuffer .= $CreateTable[$tblval][0].";\r\n";
 176              }
 177          }
 178          if ($toBackUp != "structure") {
 179              if ($OutType == 'html') {
 180                  $OutBuffer .= "<div align=\"left\">";
 181                  $OutBuffer .= "<table cellspacing=\"0\" cellpadding=\"2\" border=\"1\">";
 182                  // @RawSQLUse, trivial_implementation, SELECT
 183                  $database->setQuery("SELECT * FROM $tblval");
 184                  $rows = $database->loadObjectList();
 185  
 186                  $OutBuffer .= "<tr><th colspan=\"".count( @array_keys( @$rows[0] ) )."\">`$tblval`</th></tr>";
 187                  if (count( $rows )) {
 188                      $OutBuffer .= "<tr>";
 189                      foreach($rows[0] as $key => $value) {
 190                          $OutBuffer .= "<th>$key</th>";
 191                      }
 192                      $OutBuffer .= "</tr>";
 193                  }
 194  
 195                  if ($rows) foreach($rows as $row)
 196                  {
 197                      $OutBuffer .= "<tr>";
 198                      foreach (get_object_vars($row) as $key=>$value)
 199                      {
 200                          $value = addslashes( $value );
 201                          $value = str_replace( "\n", '\r\n', $value );
 202                          $value = str_replace( "\r", '', $value );
 203  
 204                          $value = htmlspecialchars( $value );
 205  
 206                          if (preg_match ("/\b" . $FieldType[$tblval][$key] . "\b/i", "DATE TIME DATETIME CHAR VARCHAR TEXT TINYTEXT MEDIUMTEXT LONGTEXT BLOB TINYBLOB MEDIUMBLOB LONGBLOB ENUM SET"))
 207                          {
 208                              $OutBuffer .= "<td>'$value'</td>";
 209                          }
 210                          else
 211                          {
 212                              $OutBuffer .= "<td>$value</td>";
 213                          }
 214                      }
 215                      $OutBuffer .= "</tr>";
 216                  }
 217                  $OutBuffer .= "</table></div><br />";
 218              } else {
 219                  $OutBuffer .= "#\n# Dumping data for table `$tblval`\n#\n";
 220                  // @RawSQLUse, trivial_implementation, SELECT
 221                  $database->setQuery("SELECT * FROM $tblval");
 222                  $rows = $database->loadObjectList(); if (!$rows) $rows = array();
 223                  foreach($rows as $row)
 224                  {
 225                      $InsertDump = "INSERT INTO $tblval VALUES (";
 226                      //$arr = mosObjectToArray($row);
 227                      //foreach($arr as $key => $value)
 228                      foreach (get_object_vars($row) as $key=>$value)
 229                      {
 230                          $value = addslashes( $value );
 231                          $value = str_replace( "\n", '\r\n', $value );
 232                          $value = str_replace( "\r", '', $value );
 233                          if (preg_match ("/\b" . $FieldType[$tblval][$key] . "\b/i", "DATE TIME DATETIME CHAR VARCHAR TEXT TINYTEXT MEDIUMTEXT LONGTEXT BLOB TINYBLOB MEDIUMBLOB LONGBLOB ENUM SET"))
 234                          {
 235                              $InsertDump .= "'$value',";
 236                          }
 237                          else
 238                          {
 239                              $InsertDump .= "$value,";
 240                          }
 241                      }
 242                      $OutBuffer .= rtrim($InsertDump,',') . ");\n";
 243                  }
 244              }
 245          }
 246      }
 247  
 248      /* Send the HTML headers */
 249      if ($OutDest == "remote") {
 250          // dump anything in the buffer
 251          @ob_end_clean();
 252          ob_start();
 253          header('Content-Type: ' . $mime_type);
 254          header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
 255  
 256          if ($UserBrowser == 'IE') {
 257              header('Content-Disposition: inline; filename="' . $filename . '"');
 258              header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
 259              header('Pragma: public');
 260          } else {
 261              header('Content-Disposition: attachment; filename="' . $filename . '"');
 262              header('Pragma: no-cache');
 263          }
 264      }
 265  
 266      if ($OutDest == "screen" || $OutType == "html" ) {
 267          if ($OutType == "html") {
 268                  echo $OutBuffer;
 269          } else {
 270              $OutBuffer = str_replace("<","&lt;",$OutBuffer);
 271              $OutBuffer = str_replace(">","&gt;",$OutBuffer);
 272              ?>
 273              <form>
 274                  <textarea rows="20" cols="80" name="sqldump"  style="background-color:#e0e0e0"><?php echo $OutBuffer;?></textarea>
 275                  <br />
 276                  <input type="button" onclick="javascript:this.form.sqldump.focus();this.form.sqldump.select();" class="button" value="Select All" />
 277              </form>
 278              <?php
 279          }
 280          exit();
 281      }
 282              
 283      switch ($OutType) {
 284          case "sql" :
 285              if ($OutDest == "local") {
 286                  $fp = fopen("$local_backup_path/$filename", "w");
 287                  if (!$fp) {
 288                      HTML_dbadmin::showDbAdminMessage(sprintf(T_('Database backup FAILURE!!<br />File %s/%s not writable<br />Please contact your admin/webmaster!</p>'),$local_backup_path,$filename),T_('DB Admin'),$option,$task);
 289                      return;
 290                  } else {
 291                      fwrite($fp, $OutBuffer);
 292                      fclose($fp);
 293                      HTML_dbadmin::showDbAdminMessage(sprintf(T_('Database backup successful! Your file was saved on the server in directory :<br />%s/%s</p>'),$local_backup_path,$filename),T_('DB Admin'),$option,$task);
 294                      return;
 295                  }
 296              } else {
 297                  echo $OutBuffer;
 298                  ob_end_flush();
 299                  ob_start();
 300                  // do no more
 301                  exit();
 302              }
 303              break;
 304          case "bzip" :
 305              if (function_exists('bzcompress')) {
 306                  if ($OutDest == "local") {
 307                      $fp = fopen("$local_backup_path/$filename", "wb");
 308                      if (!$fp) {
 309                          echo "<p align=\"center\"  class=\"error\">".sprintf(T_('Database backup FAILURE!!<br />File %s/%s not writable<br />Please contact your admin/webmaster!'),$local_backup_path,$filename)."</p>";
 310                      } else {
 311                          fwrite($fp, bzcompress($OutBuffer));
 312                          fclose($fp);
 313                          HTML_dbadmin::showDbAdminMessage(sprintf(T_('Database backup successful! Your file was saved on the server in directory :<br />%s/%s</p>'),$local_backup_path,$filename),T_('DB Admin'), $option,$task);
 314                          return;
 315                      }
 316                  } else {
 317                      echo bzcompress($OutBuffer);
 318                      ob_end_flush();
 319                      ob_start();
 320                      // do no more
 321                      exit();
 322                  }
 323              } else {
 324                  echo $OutBuffer;
 325              }
 326              break;
 327          case "gzip" :
 328              if (function_exists('gzencode')) {
 329                  if ($OutDest == "local") {
 330                      $fp = gzopen("$local_backup_path/$filename", "wb");
 331                      if (!$fp) {
 332                          HTML_dbadmin::showDbAdminMessage(sprintf(T_('Database backup FAILURE!!<br />File %s/%s not writable<br />Please contact your admin/webmaster!</p>'),$local_backup_path,$filename),T_('DB Admin'),$option,$task);
 333                          return;
 334                      } else {
 335                          gzwrite($fp,$OutBuffer);
 336                          gzclose($fp);
 337                          HTML_dbadmin::showDbAdminMessage(sprintf(T_('Database backup successful! Your file was saved on the server in directory :<br />%s/%s</p>'),$local_backup_path,$filename),T_('DB Admin'),$option,$task);
 338                          return;
 339                      }
 340                  } else {
 341                      echo gzencode($OutBuffer);
 342                      ob_end_flush();
 343                      ob_start();
 344                      // do no more
 345                      exit();
 346                  }
 347              } else {
 348                  echo $OutBuffer;
 349              }
 350              break;
 351          case "zip" :
 352              if (function_exists('gzcompress')) {
 353                  include  "classes/zip.lib.php";
 354                  $zipfile = new zipfile();
 355                  $zipfile -> addFile($OutBuffer, $filename . ".sql");
 356                  }
 357              switch ($OutDest) {
 358                  case "local" :
 359                      $fp = fopen("$local_backup_path/$filename", "wb");
 360                      if (!$fp) {
 361                          HTML_dbadmin::showDbAdminMessage(sprintf(T_('Database backup FAILURE!!<br />File %s/%s not writable<br />Please contact your admin/webmaster!</p>'),$local_backup_path,$filename),T_('DB Admin'),$option,$task);
 362                          return;
 363                      } else {
 364                          fwrite($fp, $zipfile->file());
 365                          fclose($fp);
 366                          HTML_dbadmin::showDbAdminMessage(sprintf(T_('Database backup successful! Your file was saved on the server in directory :<br />%s/%s</p>'),$local_backup_path,$filename),T_('DB Admin'),$option,$task);
 367                          return;
 368                      }
 369                      break;
 370                  case "remote" :
 371                      echo $zipfile->file();
 372                      ob_end_flush();
 373                      ob_start();
 374                      // do no more
 375                      exit();
 376                      break;
 377                  default :
 378                      echo $OutBuffer;
 379                      break;
 380              }
 381              break;
 382      }
 383  }
 384  
 385  function dbRestore( $local_backup_path) {
 386      global $database;
 387  
 388      $uploads_okay = (function_exists('ini_get')) ? ((strtolower(ini_get('file_uploads')) == 'on' || ini_get('file_uploads') == 1) && intval(ini_get('upload_max_filesize'))) : (intval(@get_cfg_var('upload_max_filesize')));
 389      if ($uploads_okay)
 390      {
 391          $enctype = " enctype=\"multipart/form-data\"";
 392      }
 393      else
 394      {
 395          $enctype = '';
 396      }
 397  
 398      HTML_dbadmin::restoreIntro($enctype,$uploads_okay,$local_backup_path);
 399  }
 400  
 401  function doRestore( $file, $uploadedFile, $local_backup_path ) {
 402      global $database, $option,$task,$mosConfig_absolute_path;
 403  
 404      if(!is_null($uploadedFile) && is_array($uploadedFile) && $uploadedFile["name"] != "")
 405      {
 406          $base_Dir = $mosConfig_absolute_path . "/uploadfiles/";
 407          if (!move_uploaded_file($uploadedFile['tmp_name'], $base_Dir . $uploadedFile['name']))
 408          {
 409              HTML_dbadmin::showDbAdminMessage(T_('Error! could not move uploaded file.</p>'),T_('DB Admin - Restore'),$option,$task);
 410              return false;
 411          }
 412  
 413      }
 414      if ((!$file) && (!$uploadedFile['name']))
 415      {
 416          HTML_dbadmin::showDbAdminMessage(T_('Error! No restore file specified.</p>'),T_('DB Admin - Restore'),$option,$task);
 417          return;
 418      }
 419  
 420      if ($file)
 421      {
 422          if (isset($local_backup_path))
 423          {
 424              $infile        = $local_backup_path . "/" . $file;
 425              $upfileFull    = $file;
 426              $destfile = $mosConfig_absolute_path . "/uploadfiles/$file";
 427  
 428              // If it's a zip file, we copy it so we can extract it
 429              if(eregi(".\.zip$",$upfileFull))
 430              {
 431                  copy($infile,$destfile);
 432              }
 433          }
 434          else
 435          {
 436              HTML_dbadmin::showDbAdminMessage(T_('Error! Backup path in your configuration file has not been configured.</p>'),T_('DB Admin - Restore'),$option,$task);
 437              return;
 438          }
 439      }
 440      else
 441      {
 442  
 443          $upfileFull    = $uploadedFile['name'];
 444          $infile    = $base_Dir . $uploadedFile['name']; 
 445          
 446      }
 447  
 448      if (!eregi(".\.sql$",$upfileFull) && !eregi(".\.bz2$",$upfileFull) && !eregi(".\.gz$",$upfileFull) && !eregi(".\.zip$",$upfileFull))
 449      {
 450          HTML_dbadmin::showDbAdminMessage(sprintf(T_('Error! Invalid file extension in input file (%s).<br />Only *.sql, *.bz2, or *.gz files may be uploaded.</p>'),$upfileFull),T_('DB Admin - Restore'),$option,$task);
 451          return;
 452      }
 453      
 454      if (substr($upfileFull,-3)==".gz")
 455      {
 456          if (function_exists('gzinflate'))
 457          {
 458              $fp=fopen("$infile","rb");
 459              if ((!$fp) || filesize("$infile")==0)
 460              {
 461                  HTML_dbadmin::showDbAdminMessage(sprintf(T_('Error! Unable to open input file (%s) for reading or file contains no records.</p>'),$infile),T_('DB Admin - Restore'),$option,$task);
 462                  return;
 463              }
 464              else
 465              {
 466                  $content = fread($fp,filesize("$infile"));
 467                  fclose($fp);
 468                  $content = gzinflate(substr($content,10));
 469              }
 470          }
 471          else
 472          {
 473              HTML_dbadmin::showDbAdminMessage(T_('Error! Unable to process gzip file as gzinflate function is unavailable.</p>'),T_('DB Admin - Restore'),$option,$task);
 474              return;
 475          }
 476      }
 477      elseif (substr($upfileFull,-4)==".bz2")
 478      {
 479          if (function_exists('bzdecompress'))
 480          {
 481              $fp=fopen("$infile","rb");
 482              if ((!$fp) || filesize("$infile")==0)
 483              {
 484                  HTML_dbadmin::showDbAdminMessage(sprintf(T_('Error! Unable to open input file (%s) for reading or file contains no records.</p>'),$infile),T_('DB Admin - Restore'),$option,$task);
 485                  return;
 486              }
 487              else
 488              {
 489                  $content=fread($fp,filesize("$infile"));
 490                  fclose($fp);
 491                  $content=bzdecompress($content);
 492              }
 493          }
 494          else
 495          {
 496              HTML_dbadmin::showDbAdminMessage(T_('Error! Unable to process bzip file as bzdecompress function is unavailable.</p>'),T_('DB Admin - Restore'),$option,$task);
 497              return;
 498          }
 499      }
 500      elseif (substr($upfileFull,-4)==".sql")
 501      {
 502  echo T_('trying to access').' '.$infile;
 503          $fp=fopen("$infile","r");
 504          if ((!$fp) || filesize("$infile")==0)
 505          {
 506              HTML_dbadmin::showDbAdminMessage(sprintf(T_('Error! Unable to open input file (%s) for reading or file contains no records.</p>'),$infile),T_('DB Admin - Restore'),$option,$task);
 507              return;
 508          }
 509          else
 510          {
 511              $content=fread($fp,filesize("$infile"));
 512              fclose($fp);
 513          }
 514      }
 515      elseif (substr($upfileFull,-4)==".zip")
 516      {
 517          // unzip the file
 518          $base_Dir        = $mosConfig_absolute_path . "/uploadfiles/";
 519          $archivename    = $base_Dir . $upfileFull;
 520          $tmpdir            = uniqid("dbrestore_");
 521  
 522          $isWindows = (substr(PHP_OS, 0, 3) == 'WIN' && stristr ( $_SERVER["SERVER_SOFTWARE"], "microsoft"));
 523          if($isWindows)
 524          {
 525              $extractdir    = str_replace('/','\\',$base_Dir . "$tmpdir/");
 526              $archivename = str_replace('/','\\',$archivename);
 527          }
 528          else
 529          {
 530              $extractdir    = str_replace('\\','/',$base_Dir . "$tmpdir/");
 531              $archivename = str_replace('\\','/',$archivename);
 532          }
 533  
 534          $zipfile    = new PclZip($archivename);
 535          if($isWindows)
 536              define('OS_WINDOWS',1);
 537  
 538          $ret = $zipfile->extract(PCLZIP_OPT_PATH,$extractdir);
 539          if($ret == 0)
 540          {
 541              HTML_dbadmin::showDbAdminMessage(sprintf(T_('Unrecoverable error \'%s\''),$zipfile->errorName(true)),T-('DB Admin - Restore'),$option,$task);
 542              return false;
 543          }
 544          $filesinzip = $zipfile->listContent();
 545          if(is_array($filesinzip) && count($filesinzip) > 0)
 546          {
 547              $fp            = fopen($extractdir . $filesinzip[0]["filename"],"r");
 548              $content    = fread($fp,filesize($extractdir . $filesinzip[0]["filename"]));
 549              fclose($fp);
 550  
 551              // Cleanup temp extract dir
 552              deldir($extractdir);
 553              //unlink($mosConfig_absolute_path . "uploadfiles/$file");
 554  
 555          }
 556          else
 557          {
 558              HTML_dbadmin::showDbAdminMessage(sprintf(T_('No SQL file found in %s'),$upfileFull),T_('DB Admin - Restore'),$option,$task);
 559              return;
 560          }
 561      }
 562      else
 563      {
 564          HTML_dbadmin::showDbAdminMessage(sprintf(T_('Error! Unrecognized input file type. (%s : %s)</p>'),$infile,$upfileFull),T_('DB Admin - Restore'),$option,$task);
 565          return;
 566      }
 567  
 568  
 569      $decodedIn    = explode(chr(10),$content);
 570      $decodedOut    = "";
 571      $queries    = 0;
 572  
 573      foreach ($decodedIn as $rawdata)
 574      {
 575          $rawdata=trim($rawdata);
 576          if (($rawdata!="") && ($rawdata{0}!="#"))
 577          {
 578              $decodedOut .= $rawdata;
 579              if (substr($rawdata,-1)==";")
 580              {
 581                  if  ((substr($rawdata,-2)==");") || (strtoupper(substr($decodedOut,0,6))!="INSERT"))
 582                  {
 583                      if (eregi('^(DROP|CREATE)[[:space:]]+(IF EXISTS[[:space:]]+)?(DATABASE)[[:space:]]+(.+)', $decodedOut))
 584                      {
 585                          HTML_dbadmin::showDbAdminMessage(T_('Error! Your input file contains a DROP or CREATE DATABASE statement. Please delete these statements before trying to restore the file.</p>'),T_('DB Admin - Restore'),$option,$task);
 586                          return;
 587                      }
 588                      $database->setQuery($decodedOut);
 589                      $database->query();
 590                      $decodedOut="";
 591                      $queries++;
 592                  }
 593              }
 594          }
 595      }
 596      HTML_dbadmin::showDbAdminMessage(sprintf(T_('Success! Database has been restored to the backup you requested (%d SQL queries processed).</p>'),$queries),T_('DB Admin - Restore'),$option,$task);
 597      return;
 598  }
 599  
 600  function deldir($dir)
 601  {
 602      $current_dir = opendir($dir);
 603      while($entryname = readdir($current_dir))
 604      {
 605          if(is_dir("$dir/$entryname") and ($entryname != "." and $entryname!=".."))
 606          {
 607              deldir("$dir}/$entryname}");
 608          }
 609          elseif($entryname != "." and $entryname!="..")
 610          {
 611              unlink("$dir}/$entryname}");
 612          }
 613      }
 614      closedir($current_dir);
 615      rmdir($dir);
 616  }
 617  
 618  function xquery( $option ) {
 619      global $database;
 620  
 621      $rows = null;
 622      $msg = '';
 623      $sql = trim( mosGetParam( $_POST, 'sql', '' ) );
 624      $batch = intval( mosGetParam( $_POST, 'batch', 0 ) );
 625  
 626      $allowed = array( "CREATE", "SELECT", "INSERT", "UPDATE", "DROP", "ALTER" );
 627      $words = preg_split( "/\s+/", $sql );
 628      $cmd = strtoupper( $words[0] );
 629  
 630      if ($sql == "") {
 631          $msg = T_('The query was empty.');
 632      } else if (!in_array( $cmd, $allowed)) {
 633          $msg = sprintf(T_('You are not permitted to execute a <strong>%s</strong> query'),$cmd);
 634      } else {
 635          $database->setQuery( $sql );
 636          if ($batch) {
 637              // run batch, don't abort on error
 638              $r = $database->query_batch( false );
 639          } else {
 640              $r = $database->query();
 641          }
 642          if ($r) {
 643              $msg = T_('The query executed successfully.');
 644              $msg .= sprintf(T_('<br />%d rows where affected.'),intval( $database->getNumRows() ));
 645  
 646              if ($cmd == "SELECT") {
 647                  $rows = $database->loadObjectList();
 648              }
 649          } else {
 650              $msg = sprintf(T_('The query was unsuccessful.  It return the error code %d'),$database->getErrorNum());
 651              $msg .= "<br />" . $database->getErrorMsg() . "";
 652          }
 653      }
 654  
 655      HTML_dbadmin::xquery( $sql, $msg, $rows, $option );
 656  }
 657  ?>