<?php

//Path Default
//require_once __DIR__ . "/Includes/constants.php"; //we stop it and use above to fix for symbolic link
require_once __DIR__ . "/autoload.smart.php";
//$dir_dump = 'C:\wamp\bin\mysql\mysql5.6.17\bin'; // where mysqldump.exe exist
$dir_zip = is_windows_operating_system() ? (__DIR__ . "/7z.exe") : "zip";
//Connection String
$host = DB_HOST;
$user = DB_USER;
$pass = DB_PASS;
$dbname = DB_NAME;
//
$dir_export = $mysql_dump = '';
require LIBS_PATH . 'Common/db_standalone_class.php';
$db = new db_standalone(null, $host, $user, $pass, $dbname);
$stmt = $db->query_execute("SELECT setting_name, setting_value FROM tbl_default_settings
                WHERE setting_name in ('backup_db_export_path', 'backup_mysqldump_path') ");
while ($stng_row = $db->query_fetch($stmt)) {
    if ($stng_row['setting_name'] == 'backup_db_export_path')
        $dir_export = $stng_row['setting_value'];
    elseif ($stng_row['setting_name'] == 'backup_mysqldump_path')
        $mysql_dump = $stng_row['setting_value'];
}
//
if (empty($dir_export))
    $dir_export = is_windows_operating_system() ? 'D:\backup_trusto' : upload_path;
$is_download = !empty($_GET['is_download']);
if ($is_download)
    $dir_export = upload_path;
//
if (empty($mysql_dump))
    $mysql_dump = get_mysqldump_path();
$export = $dir_export . DIRECTORY_SEPARATOR . $dbname;
$time = date('Y-m-d@H-i-s');
$db_file = "{$export}@{$time}.sql";
$zip_file = "{$export}@{$time}.zip";
//if host is with port ex: localhost:3306, then we must put the port in mysqldump path
$tmp_db_host = $host;
$tmp_db_port = '';
$tmp_port_sep_pos = strpos($host, ':');
if ($tmp_port_sep_pos !== false) {
    $tmp_db_host = substr($host, 0, $tmp_port_sep_pos);
    $tmp_db_port = substr($host, $tmp_port_sep_pos + 1);
}
//execution command to specific path and  put as zip file with password | we can echo exec or return result but add at last command " 2>&1"
exec("\"{$mysql_dump}\" {$dbname} --routines --result-file=\"{$db_file}\" --host=\"{$tmp_db_host}\" " . (empty($tmp_db_port) ? "" : " --port=\"{$tmp_db_port}\" ") . " --user=\"{$user}\" " . (empty($pass) ? "" : " -p\"{$pass}\" ") . " ");
if (is_windows_operating_system())
    exec("\"{$dir_zip}\" " . (empty($pass) ? "" : " -p\"{$pass}\" ") . " a \"{$zip_file}\" \"{$db_file}\" ");
else
    exec("{$dir_zip} " . (empty($pass) ? "" : " -P \"{$pass}\" ") . " -j -r \"{$zip_file}\" \"{$db_file}\" ");
exec((is_windows_operating_system() ? "del" : "rm") . " \"{$db_file}\"");

//
if ($is_download) {
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary");
    header("Content-disposition: attachment; filename=\"" . basename($zip_file) . "\"");
    readfile($zip_file);
    unlink($zip_file);
}

/**
 * Functions
 */
function is_windows_operating_system() {
    return strtoupper(substr(PHP_OS/* php_uname('s') */, 0, 3)) === 'WIN';
}

//
function get_mysqldump_path() {
    $main_path = dirname(dirname(dirname(__FILE__)));
    $mysqldump_path = 'mysqldump';
    if (is_windows_operating_system()) {
        $tmp_mysqldump_path = $main_path . '/mysql/bin/mysqldump.exe';
        if (file_exists($tmp_mysqldump_path)) //for xampp
            $mysqldump_path = $tmp_mysqldump_path;
        else {   //for wamp ex: C:\wamp\bin\mysql\mysql5.6.17\bin
            $tmp_mysqldump_path = $main_path . '/bin/mysql/';
            $dirs = glob($tmp_mysqldump_path . '*', GLOB_ONLYDIR);
            foreach ($dirs as $dir) {
                $tmp_mysqldump_path = $dir . '/bin/mysqldump.exe';
                if (substr(basename($dir), 0, 5) == 'mysql' && file_exists($tmp_mysqldump_path)) {
                    $mysqldump_path = $tmp_mysqldump_path;
                    break;
                }
            }
        }
    }
    return $mysqldump_path;
}
