require_once 'include/db_backup/ftp.php';
require_once 'include/database/PearDatabase.php';
require_once 'user_privileges/enable_backup.php';
global $adb, $enable_backup;
if (isset($_REQUEST['backupnow'])) {
    define("dbserver", $dbconfig['db_hostname']);
    define("dbuser", $dbconfig['db_username']);
    define("dbpass", $dbconfig['db_password']);
    define("dbname", $dbconfig['db_name']);
    $path_query = $adb->pquery("SELECT * FROM vtiger_systems WHERE server_type = ?", array('local_backup'));
    $path = $adb->query_result($path_query, 0, 'server_path');
    $currenttime = date("Ymd_His");
    if (is_dir($path) && is_writable($path)) {
        $fileName = $path . '/backup_' . $currenttime . '.zip';
        $createZip = new createDirZip();
        $createZip->addDirectory('user_privileges/');
        $createZip->get_files_from_folder('user_privileges/', 'user_privileges/');
        $createZip->addDirectory('storage/');
        $createZip->get_files_from_folder('storage/', 'storage/');
        $backup_DBFileName = "sqlbackup_" . $currenttime . ".sql";
        $dbdump = new DatabaseDump(dbserver, dbuser, dbpass);
        $dumpfile = 'backup/' . $backup_DBFileName;
        $dbdump->save(dbname, $dumpfile);
        $filedata = implode("", file('backup/' . $backup_DBFileName));
        $createZip->addFile($filedata, $backup_DBFileName);
        $fd = fopen($fileName, 'wb');
        $out = fwrite($fd, $createZip->getZippedfile());
        fclose($fd);
        $smarty->assign("BACKUP_RESULT", '<b><font color="red">' . $fileName . '</font></b>');
    } else {
        $smarty->assign("BACKUP_RESULT", '<b><font color="red">Failed to backup</font></b>');