<?php

// new startup: begin
define('REL_PATH', 'admin/backup');
$relation_level = count( explode('/', REL_PATH) );
define('FULL_PATH', realpath(dirname(__FILE__) . str_repeat('/..', $relation_level) ) );
require_once FULL_PATH.'/kernel/startup.php';
// new startup: end

$pathtolocal = $pathtoroot."kernel/";
require_once ($pathtoroot."admin/include/elements.php");
require_once ($pathtoroot."kernel/admin/include/navmenu.php");
require_once ($pathtolocal."admin/include/navmenu.php");
require_once ($pathtoroot."admin/toolbar.php");


global $tables;
unset($tables);

//$m = GetModuleArray();
//foreach($m as $key => $value)
//{	
//    $mod = $pathtoroot . $value . "admin/include/backup.php";		
//    require_once($mod);
//}

$section = "in-portal:backup_toolbar";
$envar = "env=" . BuildEnv();
$sec = $objSections->GetSection($section);

$title = admin_language("la_performing_backup")." - ".admin_language("la_Step")." 2";

int_header(NULL,NULL,$title);

/*******************************BEGINNING*********************************/

$conn = &GetADODBConnection();


$tables = $conn->MetaTables(); //  array_keys($tables);
//echo "<pre>"; print_r($tables); echo "</pre>";
$prefix = GetTablePrefix();
//if(strlen($prefix))
//{
  for($x=0;$x<count($tables);$x++)
  {  
  	if(substr($tables[$x],0,strlen($prefix))==$prefix)
  	{
  	  	if (!strstr($tables[$x], 'ses_')) {
  			$TableNames[] = $tables[$x];
  	  	}
  	}
  }
//}
$num_tables = count($TableNames);
$tables = $TableNames;

$TableIndex = (int)$_GET["TableIndex"];
$SqlStart = (int)$_GET["Start"];
$filename=$objSession->GetVariable("backup_filename");
$filepath=$objConfig->Get("Backup_Path");

$filename = $filepath."/".$filename;
$PageTitle = admin_language("la_text_Backup_in_progress");
$CancelURL =   $rootURL ."admin/backup/backup1.php?".$envar ;

if ($success==1) 
{
    finish();
}


$CurrentTable = $TableNames[$TableIndex];
$NumItems = TableCount($CurrentTable,"",0);

$caption = admin_language("la_Text_backing_up")." ".$CurrentTable." (".$NumItems." ".admin_language("la_Text_Rows").") ";
stats($caption,$SqlStart,$NumItems);
$out = array();

$caption = admin_language("la_Text_Table")." ".$TableIndex." ".admin_language("lu_of")." ".$num_tables." ";
stats($caption,$TableIndex,$num_tables);

if($SqlStart==0 && $TableIndex==0)
{
	for($x=0;$x<count($TableNames);$x++) {
		if (!strstr($TableNames[$x], 'ses_')) {
			$out[] = GetTableCreate($conn,$TableNames[$x]);	
		}
	}
}

if (!strstr($CurrentTable, 'ses_')) {
	$RowCount = insert_data($CurrentTable,$SqlStart,50,"");
}
	
$fp = fopen($filename,"a");

if (filesize($filename) == 0) {
	$ado = &GetADODBConnection();
	$sql = "SELECT Name, Version FROM ".GetTablePrefix()."Modules";
	$r = $ado->Execute($sql);
	while ($r && !$r->EOF) {
		$version = $r->fields['Version'];
		fwrite($fp, "# ".$r->fields['Name']." Version: $version;\n");
		$r->MoveNext();
	}
	fwrite($fp, "#------------------------------------------\n\n");
}

if($fp)
{
	fwrite($fp,implode("\n",$out));
	fwrite($fp,"\n");
	fclose($fp);
}
else 
{
  echo "Error opening $filename <br>\n";
  exit();
}

$SqlStart += $RowCount;
if($SqlStart>=$NumItems)
{
	$SqlStart = 0;
	$TableIndex++;
}

if($TableIndex < $num_tables)
{
	$url = $adminURL."/backup/backup2.php?".$envar."&TableIndex=$TableIndex&Start=$SqlStart";
}
else
{
	$url = $adminURL."/backup/backup3.php?".$envar;
}

reload($url);

echo "</BODY></HTML>\n";

//extracts the rows of data from tables using limits 
function insert_data($table, $start, $limit, $mywhere)
{
	global $out;
	
    $conn = &GetADODBConnection();

    if ($mywhere !="")
    {
        $whereclause= " WHERE ".$mywhere." ";
    }
    else 
    {
        $whereclause = "";
    }
    
    $rs = $conn->Execute("SELECT * from $table $whereclause LIMIT $start, $limit");
	$prefix = GetTablePrefix();
    $rowcount = 0;
	while($rs && !$rs->EOF)
	{  
        $temp=$conn->GetInsertSQL($rs,$rs->fields);
		$temp=ereg_replace("\n","\\n", $temp);
		$temp=ereg_replace("\r","\\r", $temp);
		if(strlen($prefix))
		{
			$temp = str_replace("INSERT INTO $prefix","INSERT INTO ",$temp);
		}
		$out[] = $temp;
		$rs->MoveNext();
		$rowcount++;
    }
     
    return $rowcount;
}

function GetTableCreate($conn, $table, $crlf="\n")
{
    $schema_create = 'DROP TABLE IF EXISTS ' . $table . ';' . $crlf;
	$schema_create .="# --------------------------------------------------------".$crlf;
    $conn->Execute("SET SQL_QUOTE_SHOW_CREATE = 0");
    $result = $conn->Execute("SHOW CREATE TABLE $table");
    if($result && !$result->EOF) 
    {
        $tmpres        = $result->fields; // mysql_fetch_array($result);
        $pos           = strpos($tmpres["Create Table"], ' (');
        $pos2          = strpos($tmpres["Create Table"], '(');
        if ($pos2 != $pos + 1)
        {
            $pos = $pos2;
            $tmpres["Create Table"] = str_replace(",", ",\n     ", $tmpres["Create Table"]);
        }

        $tmpres["Create Table"]     = substr($tmpres["Create Table"], 0, 13)
                       . (($use_backquotes) ? $tmpres["Table"] : $tmpres["Table"])
                       . substr($tmpres["Create Table"], $pos);
        $tmpres["Create Table"]     = str_replace("\n", $crlf, $tmpres["Create Table"]);
        if (preg_match_all('((,\r?\n[\s]*(CONSTRAINT|FOREIGN[\s]*KEY)[^\r\n,]+)+)', $tmpres["Create Table"], $regs)) {
            if (!isset($sql_constraints)) {
                if (isset($GLOBALS['no_constraints_comments'])) {
                    $sql_constraints = '';
                } else {
                    $sql_constraints = $crlf . '#' . $crlf
                                        . '# ' . $GLOBALS['strConstraintsForDumped'] . $crlf
                                        . '#' . $crlf;
                }
            }
            if (!isset($GLOBALS['no_constraints_comments'])) {
                $sql_constraints .= $crlf .'#' . $crlf .'# ' . $GLOBALS['strConstraintsForTable'] . ' ' . $table . $crlf . '#' . $crlf;
            }
            $sql_constraints .= 'ALTER TABLE $table $crlf '
                             . preg_replace('/(,\r?\n|^)([\s]*)(CONSTRAINT|FOREIGN[\s]*KEY)/', '\1\2ADD \3', substr($regs[0][0], 2))
                            . ";\n";
            $tmpres["Create Table"]     = preg_replace('((,\r?\n[\s]*(CONSTRAINT|FOREIGN[\s]*KEY)[^\r\n,]+)+)', '', $tmpres["Create Table"]);
        }
        $schema_create .= $tmpres["Create Table"];
    }
	unset($rs);
	if(strlen($schema_create))
	{
		$schema_create = str_replace("DROP TABLE IF EXISTS ".GetTablePrefix(),"DROP TABLE ",$schema_create);
		$schema_create = str_replace("CREATE TABLE ".GetTablePrefix(),"CREATE TABLE ",$schema_create);	
		while(strlen($schema_create && substr($schema_create,-1)!=")"))
		{
			$schema_create = substr($schema_create,0,-1);
		}	
	}
	$schema_create .= "\n# --------------------------------------------------------\n";
    return $schema_create;
}

function stats($caption,$myprogress,$totalnum)
{
    global $rootURL, $CancelURL,$PageTitle;
    
    if($totalnum>0)
    {
      $pct=round(($myprogress/ $totalnum)*100);
    }
    else
    $pct = 100;
    $o .="<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\" class=\"tableborder\">";
    
    echo "\n";   
    $o .= int_subsection_title_ret($caption."-".$pct."%");
    $o .= "<TR><TD  align=\"middle\"><br />"; 
    $o .= "  <TABLE CLASS=\"tableborder_full\" width=\"75%\">";
    $o .="  <TR border=1><TD width=\"".$pct."%\" STYLE=\"background:url('".$rootURL."admin/images/progress_bar_segment.gif');\">&nbsp;</TD>";
    $comp_pct = 100-$pct;
    $o .= "  <TD bgcolor=#FFFFFF width=\"".$comp_pct."%\"></TD></TR>";
    $o .= "  </TABLE>";
    $o .= "  <BR /><input type=button VALUE=\"".admin_language("la_Cancel")."\" CLASS=\"button\" ONCLICK=\"document.location='".$CancelURL."';\">";
    echo $o."\n";
    echo "</TD></TR></TABLE>";

}
function reload($url)
{
	print "<script language=\"javascript\">" ;
	print "setTimeout(\"document.location='$url';\",40);";
	print " </script>";
	//echo "<A HREF=\"$url\">Next </A>";
}

?>