<?php

/**
 *
 * INDEXU
 * Copyright(C), Nicecoder, 2000-2006, All Rights Reserved.
 *
 * INDEXU(tm) is protected by Indonesia and International copyright laws.
 * Unauthorized use or distribution of INDEXU(tm) is strictly prohibited,
 * violators will be prosecuted. To obtain a license for using INDEXU(tm),
 * please register at Nicecoder home page at http://www.nicecoder.com
 *
 * Author:
 *    Dody Rachmat Wicaksono (dody@nicecoder.com)
 *    M. Zuber (zubby@nicecoder.com)
 *
 */

  /*===================================================
    IsGz()
  ===================================================*/

  function IsGz($file) {
    // check is it gz file
    $str = substr($file,-4);
    if($str==".zip")
      return true;
    else 
      return false;
  }


  /*===================================================
    ShowBackupForm()
  ===================================================*/

  function ShowBackupForm() {
    global $dbConn, $base_path, $admin_template_path, $backup, $file, $time, $size,
           $tbl_class, $filename;

    // create new file
    $filename = date("Ymd-His");

    // get list of backup files
    
    $files = array();
    $handle=opendir($base_path . "/backup");
    while ($file = readdir($handle)) {
      if($file==".") { }
      elseif($file=="..") { }
      else {
        if(substr($file,-8)=='.sql.zip' || substr($file,-4)=='.sql') {
          $files[] = $file;
        }
      }
    }
    closedir($handle);
    rsort($files);  
    
    // get detail file info
    $i=0;
    foreach($files as $file) {
    
      clearstatcache();
    
      $time = filemtime($base_path . "/backup/".$file);
      $size = filesize($base_path . "/backup/".$file);

      $size = $size/1024;
      $size = round($size,1);
      $time = date("d.m.Y H:i",$time);        

      if($i%2) $tbl_class = "tbl_light";
      else $tbl_class = "tbl_light2";
      $i++;
      
      $backup .= EvalTemplate($admin_template_path . "db_backup_rows.html",
        "\$file,\$time,\$size,\$tbl_class");        
    }     

    DisplayTemplate($admin_template_path . "db_backup_form.html",
      "\$backup,\$filename");
  }


  /*===================================================
    Create()
  ===================================================*/

  function Create() {
    global $base_path,$zlib,$filename;
    
    $backup = DoDBBackup();

    $file = $base_path . "backup/".$filename.".sql";
    
    if($zlib==0){
      $fp = fopen ($file,"w");
      fwrite($fp,$backup);
      fclose($fp);
    }
    elseif($zlib==1) {
      $zip= new ss_zip('',6);
      $zip->add_data("indexu.sql", $backup);
      $zip->save("{$file}.zip");
    }
  }


  /*===================================================
    Show()
  ===================================================*/

  function Show($file) {
    global $base_path;
    
    $file = $base_path . "backup/".$file;
    
    if(!IsGz($file)) {
      $lines = file($file);
    }
    else {
      $zip= new ss_zip('',6);
      $zip->open($file);
      $sql = $zip->extract_data(0);
      $lines = explode("\r\n",$sql['data']);
    }
    
    print "<pre>";
    
    foreach ($lines as $line_num => $line) {
      print htmlspecialchars($line);
    } 
    print "</pre>";
  }


  /*===================================================
    Remove()
  ===================================================*/

  function Remove($file) {
    global $base_path;
    unlink($base_path . "backup/".$file);
  }


  /*===================================================
    Download()
  ===================================================*/

  function Download($file) {
    global $base_path;
   
    // set header for download

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Type: application/zip");
    header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($base_path . "backup/".$file));
    readfile($base_path . "backup/".$file);
    RunPostFilter(__FILE__);
  }


  /*===================================================
    Restore()
  ===================================================*/

  function Restore($file) {

    // vars global configuration
    global $dbConn, $base_path, $message, $admin_template_path;
      
    // vars messages
    global $msg;

    $file = $base_path . "backup/".$file;
    
    if(!IsGz($file)) {
      $lines = file($file);
    }
    else {
      $zip= new ss_zip('',6);
      $zip->open($file);
      $sql = $zip->extract_data(0);
      $lines = explode("\n",$sql['data']);
    }

    foreach ($lines as $line_num => $line) {
      $buffer = trim($line); 
      
      if(!empty($buffer) && substr($buffer,0,1) != "#") {        
        if(substr($buffer,-1,1)==";") {
          $query .= $buffer;   
          $result = $dbConn->Execute($query);
          $query = "";
        }
        else {
          $query .= $buffer;   
        }
      }
    } 

    $message = $msg['20531']; 
    DisplayTemplate($admin_template_path . "message.html",
      "\$message");
  }


  /*===================================================
    DoDBBackup()
  ===================================================*/

  function DoDBBackup() {

    // vars global configuration
    global $dbConn, $dbHostname, $dbName, $admin_template_path;
    
    // vars url & form
    global $t;

    // vars messages

    // vars template

    // currently working with mysql only
    
    $line .= 
    $line .= "#  \n";
    $line .= "# INDEXU \n";
    $line .= "# Database backup file \n";
    $line .= "# http://www.nicecoder.com \n";
    $line .= "# \n";
    $line .= "# Host    : " . $dbHostname ."\n";
    $line .= "# Database: " . $dbName ."\n";
    $line .= "# Date    : " . date("d-M-Y",time()) . "\n";     
    $line .= "#  \n\n\n";
    
    // get tables
    $query         = "show tables";
    $dbConn->debug = false;
    $result_table  = $dbConn->Execute($query);

    while ($row_table = $result_table->FetchRow()) {
      
      $table = $row_table[key($row_table)];
      
      $line .= "#  \n";
      $line .= "# Table structure for table '$table' \n";
      $line .= "#  \n\n";
      
      $line .= "DROP TABLE IF EXISTS $table;\n";

      
      // table structure      
      $struc        = "CREATE TABLE $table (\n";
      
      $query        = "show fields from $table";
      $result_field = $dbConn->Execute($query);

      while ($row_field = $result_field->FetchRow($result_field))  {       
        $struc .= "  $row_field[Field] $row_field[Type]";
        
        if(!empty($row_field["Default"])) {
          $struc .= " DEFAULT '$row_field[Default]'";
        }
        if($row_field["Null"] != "YES") {
          $struc .= " NOT NULL";
        }
        if($row_field["Extra"] != "") {
          $struc .= " $row_field[Extra]";
        }
        $struc .= ",\n";
      }
      $result_field->Close();
      
      $query      = "show keys from $table";
      $result_key = $dbConn->Execute($query);  
      $pkey_exist = $result_key->RecordCount();
      
      if($pkey_exist!=0) {
        $pkey = $result_key->Fields('Column_name');
        $struc .= "  PRIMARY KEY ($pkey)\n";
      }
      else {
        $struc = substr($struc,0, strlen($struc)-2);      
        $struc .= "\n";
      }      
      
      $line .= $struc;
      $line .= ");\n\n";

      
      // data
      
      $line .= "#  \n";
      $line .= "# Dumping data for table '$table' \n";
      $line .= "#  \n\n";

      $query       = "select * from $table";
      $result_data = $dbConn->Execute($query);  

      $j = 0;
      $num_field = $result_data->FieldCount();
      while($row_data = $result_data->FetchRow()) {
        $data .= "INSERT INTO $table VALUES(";
        while (list($k, $v) = @each($row_data)) {
          if (is_null($v)) {
            $data .= " NULL,";
          }
          elseif($row_data[$k]!="") {
            $data .= " '".addslashes($row_data[$k])."',";
          }
          else {
            $data .= " '',";
          }
        }

        // replace ,\n
        $data = substr($data,0, strlen($data)-1);      
        $data .= ");\n";
        $j++;
      }
      $result_data->Close();
    
      $line .= $data."\n";
      $data = "";
      
      $i++;  
    }  
    
    return $line;
  }


  /*===================================================
    main
  ===================================================*/

  include "../application.php";
  include "../lib/ss_zip.class.php";
  ini_set("max_execution_time", "3600");
  
  if ($pflag == "dl") {
    RemoveFilter("gzip_compression");
    RemoveFilter("runtime");
  }
  RunPreFilter(__FILE__);
    
  if ($pflag != "dl") {
    DisplayTemplate($admin_template_path . "header.html");
  }
  
  if(empty($pflag)) {  
    ShowBackupForm(); 
  }
  elseif($pflag=='create') {
    Create();
    ShowBackupForm();
  }
  elseif($pflag=='dl') {
    Download($file);
  }
  elseif($pflag=='show') {
    Show($file);
  }
  elseif($pflag=='res') {
    Restore($file);
  }
  elseif($pflag=='del') {
    Remove($file);
    ShowBackupForm();
  }
      
  if ($pflag != "dl") {
    DisplayTemplate($admin_template_path . "footer.html");
  }

  RunPostFilter(__FILE__);

?>