<?php
ini_set('display_errors', 1);
ini_set('mysql.connect_timeout', 5000);
ini_set('default_socket_timeout', 5000);
include_once 'opendb.php';

EXPORT_DATABASE($host,$user ,$password,$dbname ); 

// by https://github.com/tazotodua/useful-php-scripts //
function EXPORT_DATABASE($host,$user,$pass,$name,       $tables=false, $backup_name=false)
{ 
    $myfile = fopen("backup/backup.sql", "w") or die("Unable to create file!");

    //set_time_limit(3000);
    $conn = new mysqli($host,$user,$pass,$name); $conn->select_db($name); $conn->query("SET NAMES 'utf8'");
    $queryTables = $conn->query('SHOW TABLES'); while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; }	if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); } 
    $content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--\r\n-- Database: `".$name."`\r\n--\r\n\r\n\r\n";
    fwrite($myfile, $content);
    fclose($myfile);
    $myfile = "backup/backup.sql"; 
    $content="";
    foreach($target_tables as $table){
        if (empty($table)){ continue; } 
        
        $chunk_size = 1000;
        $done = 0;
        $keep_asking_for_data = true;
        do{        
            $qry="SELECT * FROM `$table` LIMIT $done , $chunk_size;";       
           
            $result	= $conn->query($qry);
             if (!$result) {
                echo ($qry);
                echo ("error in select : " . mysqli_error($conn));
                exit();
             }
            $rows_num=$result->num_rows;           
            $fields_count=$result->field_count; 
            if($done == 0){
                $res = $conn->query('SHOW CREATE TABLE '.$table);	
                $TableMLine=$res->fetch_row(); 
                $content .= "\n\n".$TableMLine[1].";\n\n";   $TableMLine[1]=str_ireplace('CREATE TABLE `','CREATE TABLE IF NOT EXISTS `',$TableMLine[1]);
                file_put_contents($myfile, $content, FILE_APPEND | LOCK_EX); 
                $content="";
            }
            $st_counter=0;
             if($rows_num){
                $done +=$rows_num;
                while($row = $result->fetch_row())	{ //when started (and every after 100 command cycle):
                    if ($st_counter%100 == 0 || $st_counter == 0 )	{
                        $content .= "\nINSERT INTO ".$table." VALUES";
                    }
                    $content .= "\n("; 
                    for($j=0; $j<$fields_count; $j++){
                        $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
                        if (isset($row[$j])){$content .= '"'.$row[$j].'"' ;} else{$content .= '""';}
                        if ($j<($fields_count-1)){$content.= ',';}  
                    }
                            $content .=")";
                    //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                    if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= ";";} else {$content .= ",";}
                    $st_counter=$st_counter+1;
                    file_put_contents($myfile, $content, FILE_APPEND | LOCK_EX); 
                    $content="";  
                  
                }
             } else {
                $keep_asking_for_data = false;
            }
           // $result -> free_result();
        
        }while($keep_asking_for_data);    
        //} 
        $content .="\n\n\n";
        file_put_contents($myfile, $content, FILE_APPEND | LOCK_EX); 
        $content="";
       // echo "done : " .$table."\n\n";
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    $backup_name = $backup_name ? $backup_name : $name.'___('.date('H-i-s').'_'.date('d-m-Y').').sql';

    //header('Content-Type: application/octet-stream');  header("Content-Transfer-Encoding: Binary");  header('Content-Length: '. (function_exists('mb_strlen') ? mb_strlen($content, '8bit'): strlen($content)) );    header("Content-disposition: attachment; filename=\"".$backup_name."\""); 
    //echo $content; 
    file_put_contents($myfile, $content, FILE_APPEND | LOCK_EX); 
    ob_get_clean();
    
    $zip = new ZipArchive();
    $bfname=date("D")."-". getcwd();
    $bfname=str_replace("/","-",$bfname);
    $zfilename =  "backup/".$bfname. ".zip"; 
    
    if(file_exists($zfilename)){
        unlink($zfilename);    
    }
    if ($zip->open($zfilename, ZipArchive::CREATE)!==TRUE) {
        exit("cannot open <$zfilename>\n");
    }
    $zip->addFromString( "server.txt",getcwd());
    $zip->addFile( "backup/backup.sql");
    $options = array('add_path' => 'scripts/', 'remove_all_path' => TRUE);
    $zip->addGlob('*.{php,txt}', GLOB_BRACE, $options);
    
    $zip->close();
 //   ftpuloadbkp($zfilename,$bfname. ".zip");
  //  mailbkpfile($zfilename,$bfname. ".zip");
    header('Content-type: application/zip');
	header('Content-Disposition: attachment; filename="'.basename($zfilename).'"');
	header("Content-length: " . filesize($zfilename));
	header("Pragma: no-cache");
	header("Expires: 0");
    flush();
    readfile($zfilename);
}
function ftpuloadbkp($filename,$expfilename){
    $ftp_server = "files.000webhost.com";
    $ftp_conn = ftp_connect($ftp_server) or retun; // die("Could not connect to $ftp_server");
    $login = ftp_login($ftp_conn, "manacc", "master@123");
    $file = $filename;
    // upload file
    if (ftp_put($ftp_conn,"/public_html/backupremote/".$expfilename, $file, FTP_BINARY))
      {
     // echo "Successfully uploaded $file.";
      }
    else
      {
    //  echo "Error uploading $file.";
      }
    
    // close connection
    ftp_close($ftp_conn);
}



?>