<?php
require_once('inc/logincheck.php');
CommTool::checkIncludeByAdminPhp();
include_once('../inc/thirdpart/phpzip/pclzip.lib.php');

if("backup" == $action)
{
  $fileId = isset($fileId) ? $fileId : 1;
  if(1 == $fileId && $tables)
  {
    if(!isset($tables) || !is_array($tables))promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=backup", $promptBackUpSelectedEmptyDatabaseTable);
    $randomNum = mt_rand(1000, 9999);
    cache_write('baktables.php', $tables, KUWEBS_ADMIN_PATH."cache/");
  }
  else
  {
    if(!$tables = cache_read('baktables.php', KUWEBS_ADMIN_PATH."cache/"))promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=backup", $promptBackUpCannotWriteCache);
  }
  
  $arrFiles = array();
  $tableIndex = 1;
  $tableDump = '';
  foreach($tables as $tableInfo)
  {
    $tableDump .= "DROP TABLE IF EXISTS `$tableInfo`;\n";
    $resultCreateTable = $dbInstance->query("SHOW CREATE TABLE `$tableInfo`;");
    $rowCreateTable = $dbInstance->fetchArray($resultCreateTable);
    $tableDump .= $rowCreateTable['Create Table'].";\n\n\n";
    
    $startRow = 0;
    $offset = 100;
    $sizeLimit = isset($sizeLimit) ? $sizeLimit : 1024;
    $tableCount = $dbInstance->getCount("select count(*) from $tableInfo");
    while($startRow<$tableCount)
    {
      $result = $dbInstance->query("SELECT * FROM `$tableInfo` LIMIT $startRow, $offset;");
      $numFields = $dbInstance->numFields($result);
      $numRows = $dbInstance->numRows($result);
      while($row = $dbInstance->fetchRow($result))
      {
        $comma = "";
        $tableDump .= "INSERT INTO `$tableInfo` VALUES(";
        for($j = 0; $j < $numFields; $j++)
        {
          $tableDump .= $comma."'".mysql_escape_string($row[$j])."'";
          $comma = ",";
        }
        $tableDump .= ");\n";
      }
      $dbInstance->free_result($result);
      
      if(strlen($tableDump) > $sizeLimit*1000)
      {
        $tableDump .= "\n\n";
        
        $tableDump = "# Kuwebs.com data bak file\n# version: ".KUKWEBS_VERSION."\n# Time: ".date('Y-m-d H:i:s')."\n# Type:kuwebs\n# KuWebs: http://www.kuwebs.com\n# ----------------------------\n\n\n\n".$tableDump;
        $fileName = "kuwebs_sql_".date('YmdHis', time()).'_'.$tableIndex.'.sql';
        $tableIndex++;
        $bakFile = KUWEBS_ADMIN_PATH.'databak/'.$fileName;
        if(!is_writable(KUWEBS_ADMIN_PATH.'databak/'))promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=system&menu=onekeybackup", $promptBackUpCannotWriteDatabak);
        file_put_contents($bakFile, $tableDump);
        @chmod($bakFile, 0777);
        array_push($arrFiles, $bakFile);
        
        $tableDump = '';
      }
      
      $startRow += $offset;
      if($startRow > $tableCount)
      {
        $startRow = 0;
        break;
      }
    }
  
  }

  $tableDump .= "\n\n";
  
  $tableDump = "# Kuwebs.com data bak file\n# version: ".KUKWEBS_VERSION."\n# Time: ".date('Y-m-d H:i:s')."\n# Type:kuwebs\n# KuWebs: http://www.kuwebs.com\n# ----------------------------\n\n\n\n".$tableDump;
  $fileName = "kuwebs_sql_".date('YmdHis', time()).'_'.$tableIndex.'.sql';
  $bakFile = KUWEBS_ADMIN_PATH.'databak/'.$fileName;
  array_push($arrFiles, $bakFile);
  if(!is_writable(KUWEBS_ADMIN_PATH.'databak/'))promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=backup", $promptBackUpCannotWriteDatabak);
  file_put_contents($bakFile, $tableDump);
  @chmod($bakFile, 0777);

  //zip files and delete sql file
  $fileSql = "databak/kuwebs_sql_".date('YmdHis', time()).".zip";
  $archive1 = new PclZip($fileSql);
  foreach($arrFiles as $fileName)
  {
    $v_list = $archive1->add($fileName, PCLZIP_OPT_REMOVE_PATH, dirname($fileName));
    @unlink($fileName);
  }

  promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=backup", $promptBackUpCopyDatabaseSucess."databak/{$fileSql}", 5);

}
else if('restore' == $action)
{//extract and then restore, unlink the sql files
  $fileName = $filepre.$fileId.'.zip';
  $filePath = KUWEBS_ADMIN_PATH.'databak/'.$fileName;    
  $archive = new PclZip($filePath);
  $archive->extract(PCLZIP_OPT_PATH, dirname($filePath));
  foreach(glob(KUWEBS_ADMIN_PATH.'databak/kuwebs_sql_*.sql') as $sqlFile)
  {
    if(file_exists($sqlFile))
    {
      $strSql = file_get_contents($sqlFile);
      sqlExecute($strSql);
      promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=restore", $promptRestoreOperateSuccess);
    }
    @unlink($sqlFile);
  }
}
else if('filedown' == $action)
{
  $fileext = fileExt($filename);
  if('zip' == $fileext)
  {
    file_down(KUWEBS_ADMIN_PATH.'databak/'.$filename);
  }
}
else if('upload' == $action)
{
  
  $sqlFile = $_FILES["uploadfile"]['name'];             
  $strAtPoint = strrpos($sqlFile, ".");             
  $lenght = strlen($sqlFile) - $strAtPoint;         
  $extName = strtolower(substr($sqlFile,$strAtPoint,$lenght)); 
  if('.zip' != $extName)
  {
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=restore", $promptUploadCorrectDatabaseFormat);
    exit;
  }
  $tempName = $_FILES["uploadfile"]['tmp_name'];
  if(@move_uploaded_file("$tempName", "databak/$sqlFile"))
  {
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=restore", $promptUploadDatabaseSuccess);
    exit;
  }
  else
  {
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=restore", $promptUploadDatabaseFail);
    exit;
  }
}
else if('delete' == $action)
{
  if($filename)
  {
    if('zip' == fileExt($filename))
    {
      @unlink(KUWEBS_ADMIN_PATH.'databak/'.$filename);
      promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=restore", $promptDeleteDataSuccess);
    }
  }
  else if($filenames)
  {
    if(is_array($filenames))
    {
      foreach($filenames as $key=>$fileName)
      {
        if('zip' == fileExt($fileName))
        {
          @unlink(KUWEBS_ADMIN_PATH.'databak/'.$fileName);
        }
      }
      promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=restore", $prompBatchDeleteSuccess);
    }
  }
  else
  {
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=database&menu=restore", $promptDeleteDatabaseRestoreSuccess);
  }
}
else if("onekeybackup" == $action)
{
  $tables = array();
  $arrFiles = array();
  $i = 0;
  $totalSize = 0;
  $strSql = "show table status from $configDBName;";
  $result = $dbInstance->query($strSql);
  while($row = $dbInstance->fetchArray($result))
  {
    $tableName[$i] = $row['Name'];
    $tableCount[$i] = $row['Rows'];
    $tableSize[$i] = round($row['Data_length']/1024, 2);
    $totalSize += $tableSize[$i];
    $i++;
    array_push($tables, $row['Name']);
  }

  $fileId = isset($fileId) ? $fileId : 1;
  if(1 == $fileId && $tables)
  {
    $randomNum = mt_rand(1000, 9999);
    cache_write('baktables.php', $tables, KUWEBS_ADMIN_PATH."cache/");
  }
  else
  {
    if(!$tables = cache_read('baktables.php', KUWEBS_ADMIN_PATH."cache/"))promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=system&menu=onekeybackup", $promptBackUpCannotWriteCache);
  }
  
  $tableIndex = 1;
  $tableDump = '';
  foreach($tables as $tableInfo)
  {
    $tableDump .= "DROP TABLE IF EXISTS `$tableInfo`;\n";
    $resultCreateTable = $dbInstance->query("SHOW CREATE TABLE `$tableInfo`;");
    $rowCreateTable = $dbInstance->fetchArray($resultCreateTable);
    $tableDump .= $rowCreateTable['Create Table'].";\n\n\n";
    
    $startRow = 0;
    $offset = 100;
    $sizeLimit = isset($sizeLimit) ? $sizeLimit : 1024;
    $tableCount = $dbInstance->getCount("select count(*) from $tableInfo");
    while($startRow<$tableCount)
    {
      $result = $dbInstance->query("SELECT * FROM `$tableInfo` LIMIT $startRow, $offset;");
      $numFields = $dbInstance->numFields($result);
      $numRows = $dbInstance->numRows($result);
      while($row = $dbInstance->fetchRow($result))
      {
        $comma = "";
        $tableDump .= "INSERT INTO `$tableInfo` VALUES(";
        for($j = 0; $j < $numFields; $j++)
        {
          $tableDump .= $comma."'".mysql_escape_string($row[$j])."'";
          $comma = ",";
        }
        $tableDump .= ");\n";
      }
      $dbInstance->free_result($result);
      
      if(strlen($tableDump) > $sizeLimit*1000)
      {
        $tableDump .= "\n\n";
        
        $tableDump = "# Kuwebs.com data bak file\n# version: ".KUKWEBS_VERSION."\n# Time: ".date('Y-m-d H:i:s')."\n# Type:kuwebs\n# KuWebs: http://www.kuwebs.com\n# ----------------------------\n\n\n\n".$tableDump;
        $fileName = "kuwebs_sql_".date('YmdHis', time()).'_'.$tableIndex.'.sql';
        $tableIndex++;
        $bakFile = KUWEBS_ADMIN_PATH.'databak/'.$fileName;
        if(!is_writable(KUWEBS_ADMIN_PATH.'databak/'))promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=system&menu=onekeybackup", $promptBackUpCannotWriteDatabak);
        file_put_contents($bakFile, $tableDump);
        @chmod($bakFile, 0777);
        array_push($arrFiles, $bakFile);
        
        $tableDump = '';
      }
      
      $startRow += $offset;
      if($startRow > $tableCount)
      {
        $startRow = 0;
        break;
      }
    }
  
  }

  $tableDump .= "\n\n";
  
  $tableDump = "# Kuwebs.com data bak file\n# version: ".KUKWEBS_VERSION."\n# Time: ".date('Y-m-d H:i:s')."\n# Type:kuwebs\n# KuWebs: http://www.kuwebs.com\n# ----------------------------\n\n\n\n".$tableDump;
  $fileName = "kuwebs_sql_".date('YmdHis', time()).'_'.$tableIndex.'.sql';
  $bakFile = KUWEBS_ADMIN_PATH.'databak/'.$fileName;
  array_push($arrFiles, $bakFile);
  if(!is_writable(KUWEBS_ADMIN_PATH.'databak/'))promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=system&menu=onekeybackup", $promptBackUpCannotWriteDatabak);
  file_put_contents($bakFile, $tableDump);
  @chmod($bakFile, 0777);

  //zip files and delete sql file
  $fileSql = "databak/kuwebs_sql_".date('YmdHis', time()).".zip";
  $archive1 = new PclZip($fileSql);
  foreach($arrFiles as $fileName)
  {
    $v_list = $archive1->add($fileName, PCLZIP_OPT_REMOVE_PATH, dirname($fileName));
    @unlink($fileName);
  }
}
?>