<?php

/**
 *
 * Plugin Name: Backup Creator
 * Plugin URI: http://www.backupcreator.com
 * Description: Backup and cloning tool for WordPress blogs.
 * Version: 1.02g
 * Author: Robert Plank
 * Author URI: http://www.robertplank.com
*/

require_once(ABSPATH . WPINC . "/class-snoopy.php");
define("BACKUPCREATOR_UPGRADE_URL", "http://www.backupcreator.com/members");
define("BACKUPCREATOR_KEY_URL", "http://www.backupcreator.com/members/license-key");
define("BACKUPCREATOR_PRODUCT_NAME", "Backup Creator");
define("BACKUPCREATOR_VERSION", "1.0.2G");
define("BACKUPCREATOR_SALT", "sfg54fdc44g623p9");
define("BACKUPCREATOR_DBS", chr(92) . chr(92));
if (function_exists("wp_upload_dir")) {
    $dir   = wp_upload_dir();
    $perms = fileperms($dir["basedir"]) & 511;
    if ($perms == 0755) {
        define("BACKUPCREATOR_CHMOD", 0755);
    } else {
        define("BACKUPCREATOR_CHMOD", 0775);
    }
} else {
    define("BACKUPCREATOR_CHMOD", 0775);
}
if (!defined('WP_CONTENT_URL')) {
    define('WP_CONTENT_URL', get_option('siteurl') . '/wp-content');
}
define('BACKUPCREATOR_URL', WP_CONTENT_URL . "/plugins/" . basename(dirname(__FILE__)));
function backupcreator_call()
{
    $settings = get_option("backupcreator");
    $hash     = md5($settings["lastcheck"] . "|" . BACKUPCREATOR_SALT);
	
    if (isset($settings["key"]) && isset($settings["email"]) && isset($settings["lastcheck"]) && time() - $settings["lastcheck"] < 21600 && $settings["lasthash"] == $hash) {
        return backupcreator_version_format(BACKUPCREATOR_VERSION);
    }
    if (isset($_POST["LicenseEmail"])) {
        $email = trim($_POST["LicenseEmail"]);
    } elseif (isset($settings["email"])) {
        $email = $settings["email"];
    }
    if (isset($_POST["LicenseKey"])) {
        $key = trim($_POST["LicenseKey"]);
    } elseif (isset($settings["key"])) {
        $key = $settings["key"];
    }
    $settings["email"] = $email;
    $settings["key"]   = $key;
    update_option("backupcreator", $settings);
    if (empty($key)) {
        return "UNREGISTERED";
    }
    $site   = dirname(WP_CONTENT_URL);
    $snoopy = new Snoopy();
    $url    = "http://www.backupcreator.com/members/?wpdrip=" . $email . "|" . $key . "|Full|" . $site;
    if ($result = $snoopy->fetch($url)) {
        $results = $snoopy->results;
        if (empty($results) || $results == "UNREGISTERED" || $results == "UNKNOWN" || $results == "CANCELLED" || $results == "FAILED") {
        } else {
            $time                  = time();
            $settings["lastcheck"] = $time;
            $hash                  = md5($time . "|" . BACKUPCREATOR_SALT);
            $settings["lasthash"]  = $hash;
            update_option("backupcreator", $settings);
        }
        return backupcreator_version_format($results);
    } else {
        return null;
    }
}
function backupcreator_deactivate()
{
    $settings = get_option("backupcreator");
    unset($settings["email"]);
    unset($settings["key"]);
    unset($settings["lastcheck"]);
    unset($settings["lasthash"]);
    update_option("backupcreator", $settings);
}
function backupcreator_version_format($input)
{
    list($integer, $fraction) = explode('.', $input, 2);
    $integer  = intval($integer);
    $fraction = preg_replace('@' . chr(91) . chr(94) . '0-9' . chr(93) . '@si', '', $fraction);
    return floatval($integer . "." . $fraction);
}
function backupcreator_message($call = "")
{
 /*
	if (empty($call)) {
        $call = backupcreator_call();
    }
*/	
    $url = "options-general.php?page=" . plugin_basename(__FILE__);
    if (isset($_GET["page"]) && $_GET["page"] == $url) {
        $url = constant("BACKUPCREATOR_UPGRADE_URL");
    }
?>
<?php
    if (empty($call)):
?>
<!-- do nothing -->
<?php
    elseif ($call == "UNREGISTERED"):
?>
<div class="error">
<p><b><?php
        echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Alert:</b> You need to <a href="<?php
        echo $url;
?>">activate your license key</a> to begin using the plugin.</p>
</div>
<?php
    elseif ($call == "CANCELLED"):
?>
<div class="error">
<p><b><?php
        echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Alert:</b> Your license has been <a href="<?php
        echo $url;
?>">cancelled for non-payment</a>.</p>
</div>
<?php
    elseif ($call == "UNKNOWN"):
?>
<div class="error">
<p><b><?php
        echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Alert:</b> That email address is not found in our database, <a href="<?php
        echo $url;
?>">please double check your details</a>.</p>
</div>
<?php
    elseif ($call == "FAILED"):
?>
<div class="error">
<p><b><?php
        echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Alert:</b> <a href="<?php
        echo $url;
?>">Incorrect license key</a> for that email address.</p>
</div>
<?php
    elseif (backupcreator_version_format($call) > backupcreator_version_format(constant("BACKUPCREATOR_VERSION")) && isset($_GET["page"]) && $_GET["page"] == $url):
?>
<div class="error">
<p><?php
        echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> <?php
        echo floatval($call);
?> is available! <a target="_blank" href="<?php
        echo constant("BACKUPCREATOR_UPGRADE_URL");
?>">Please update now.</a></p>
</div>
<?php
    endif;
?>
<?php
}
function backupcreator_register($call)
{
    if (isset($_POST["LicenseEmail"])) {
        $email = $_POST["LicenseEmail"];
    } else {
        $email = get_option("admin_email");
    }
    if (isset($_POST["LicenseKey"])) {
        $key = $_POST["LicenseKey"];
    } else {
        $key = "";
    }
?>
<div class="wrap">
<h2><?php
    echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Key</h2>

<form method="post">
<table class="form-table">
	<tr valign="top">
		<td colspan="3" style="border:none">
         <p>Please enter your <?php
    echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> License Key and Email below to activate this plugin.</p>
      </td>
	</tr>
	<tr valign="top">
		<th scope="row" style="border:none;white-space:nowrap;"><?php
    echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Key</th>
		<td style="border:none"><input type="text" name="LicenseKey" value="<?php
    echo $key;
?>" size="32" /></td>
		<td style="border:none">(This was sent to the email you used during your purchase)</td>
	</tr>
	<tr valign="top">
		<th scope="row" style="border:none;white-space:nowrap"><?php
    echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Email</th>
		<td style="border:none"><input type="text" name="LicenseEmail" value="<?php
    echo $email;
?>" size="32" /></td>
		<td style="border:none">(Please enter the email you used during your registration/purchase)</td>
	</tr>
   <tr valign="top">
      <td colspan="3">
         <p><b>Note:</b> You need to enter the email address <B>you used to PURCHASE</B> <?php
    echo constant("BACKUPCREATOR_PRODUCT_NAME");
?>, not necessarily the administrator email address of this blog.</p>
      </td>
   </tr>
</table>
<p class="submit">
	<input type="submit" value="Save <?php
    echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Key" name="Submit" />
   <a target="_blank" href="<?php
    echo constant("BACKUPCREATOR_KEY_URL");
?>">Get New <?php
    echo constant("BACKUPCREATOR_PRODUCT_NAME");
?> Key</a>
</p>
</form>
</div>
<?php
}
function backupcreator_key($email)
{
    $backupcreator = get_option("backupcreator");
    $master        = $backupcreator["master"];
    return md5($email . "|" . $master);
}
@set_time_limit(300);
@ob_implicit_flush();
$backupcreator_plugin = (isset($wpdb) || function_exists("add_action"));
if (function_exists("posix_getpwuid")) {
    $backupcreator_stat  = stat(dirname(WP_CONTENT_DIR));
    $backupcreator_pwuid = posix_getpwuid($backupcreator_stat['uid']);
    $backupcreator_chown = $backupcreator_pwuid["name"];
} else {
    $backupcreator_chown = "";
}
$backupcreator_cwd = getcwd();
global $backupcreator_dir;
$backupcreator_dir = dirname(__FILE__);
if ($backupcreator_plugin) {
    $upload_dir         = wp_upload_dir();
    $backupcreator_save = $upload_dir["basedir"] . "/backupcreator";
    $backupcreator_url  = $upload_dir["baseurl"] . "/backupcreator";
    @mkdir($backupcreator_save);
    @chmod($backupcreator_save, constant("BACKUPCREATOR_CHMOD"));
    @chown($backupcreator_save, $backupcreator_stat['uid']);
    @chgrp($backupcreator_save, $backupcreator_stat['gid']);
    if ($backupcreator_chown != "") {
        @system("chown " . $backupcreator_chown . ":" . $backupcreator_chown . " " . $backupcreator_save);
    }
    if (!file_exists($backupcreator_save . "/" . ".htaccess")) {
        $fp = fopen($backupcreator_save . "/" . ".htaccess", "w");
        fwrite($fp, "IndexIgnore *");
        fclose($fp);
        @chmod($backupcreator_save . "/" . ".htaccess", constant("BACKUPCREATOR_CHMOD"));
        $fp = fopen($backupcreator_save . "/" . "index.html", "w");
        fwrite($fp, "");
        fclose($fp);
        @chmod($backupcreator_save . "/" . "index.html", constant("BACKUPCREATOR_CHMOD"));
        $fp = fopen($backupcreator_save . "/" . "index.php", "w");
        fwrite($fp, "");
        fclose($fp);
        @chmod($backupcreator_save . "/" . "index.php", constant("BACKUPCREATOR_CHMOD"));
    }
} else {
    $backupcreator_save = getcwd();
    $backupcreator_url  = "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["REQUEST_URI"]);
}
$backupcreator_filesql     = $backupcreator_save . "/backupcreatorfile-sql";
$backupcreator_tableprefix = $backupcreator_save . "/backupcreatorfile-tableprefix";
$backupcreator_sourceurl   = $backupcreator_save . "/backupcreatorfile-sourceurl";
$backupcreator_htaccess    = $backupcreator_save . "/backupcreatorfile-htaccess";
$backupcreator_oldpath     = $backupcreator_save . "/backupcreatorfile-oldpath";
global $table_prefix;
if (function_exists("site_url")) {
    $host = get_bloginfo('url');
} else {
    $host = $_SERVER["HTTP_HOST"] . dirname($_SERVER["REQUEST_URI"]);
}
$host                  = eregi_replace("^https?://", "", $host);
$host                  = eregi_replace("^www.", "", $host);
$host                  = eregi_replace("[^A-Z0-9-]+", "-", $host);
$host                  = trim($host);
$backupcreator_date    = trim(date('Ymdhis'));
$backupcreator_zipfile = "backupcreator." . trim(basename($host)) . "." . $backupcreator_date . ".zip";
if (!function_exists("backupcreator_header")) {
    function backupcreator_init()
    {
        global $backupcreator_plugin;
        if (isset($_GET["backupcreator_download"])) {
            if ($backupcreator_plugin) {
                $upload_dir = wp_upload_dir();
                $url        = $upload_dir["baseurl"] . "/backupcreator";
                $url        = dirname(WP_CONTENT_URL) . "/" . stripslashes(rawurldecode($_GET["backupcreator_download"]));
            } else {
                $url = $_SERVER["HTTP_HOST"] . dirname($_SERVER["REQUEST_URI"]) . "/" . basename(stripslashes(rawurldecode($_GET["backupcreator_download"])));
            }
            if (function_exists("wp_upload_dir")) {
                $upload_dir = wp_upload_dir();
                $url        = $upload_dir["baseurl"] . "/backupcreator/" . basename(stripslashes(rawurldecode($_GET["backupcreator_download"])));
            }
            if (preg_match('@["\n\r]@', $url)) {
                die("Invalid URL.");
            }
            if (ini_get('zlib.output_compression')) {
                ini_set('zlib.output_compression', 'Off');
            }
            $contents = file_get_contents(__FILE__);
            $contents = preg_replace('@(\$backupcreator\_import = ")([^"]*)(";)@i', '\1' . $url . '\3', $contents);
            $zipFile  = tempnam("tmp", "zip");
            $zip      = new ZipArchive();
            $zip->open($zipFile, ZipArchive::OVERWRITE);
            $zip->addFromString("backupcreator.php", $contents);
            $zip->close();
            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: inline; filename="backupcreator.zip";');
            header('Content-Description: File Transfer');
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: " . filesize($zipFile));
            flush();
            readfile($zipFile);
            unlink($zipFile);
            die();
        }
    }
    function backupcreator_header($title = "")
    {
        global $backupcreator_plugin;
        $self = "options-general.php?page=" . plugin_basename(__FILE__);
        if ($backupcreator_plugin) {
?>
         <?php
            if ($title != ""):
?>
         <h2><a href="<?php
                echo $self;
?>">Backup Creator</a>: <?php
                echo $title;
?></h2>
         <?php
            else:
?>
         <h2>Backup Creator</h2>
         <?php
            endif;
?>

         <?php
            return;
        }
?>
   <style type="text/css">
   <!--
      body {
       font: 14px "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
   }

   h1, h2 { text-align:center; }

      form {
       background: none repeat scroll 0 0 #FFFFFF;
       border: 1px solid #E5E5E5;
       border-radius: 11px 11px 11px 11px;
       box-shadow: 0 4px 18px #C8C8C8;
       font-weight: normal;
       padding-top: 0;
       padding-bottom:0;
       padding-left:32px;
       padding-right:32px;
      }

   #backupcreator {
       margin: 7em auto;
       width: 700px;
       overflow:visible;
   }

   .button-primary {
       border: black 1px solid;
       cursor: pointer;
       font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
       font-size: 18px;
       margin-top: -3px;
       padding: 3px 10px;
       text-decoration: none;
       color: #FFFFFF;
       font-weight: bold;
       background-color:#298CBA;
   }
   -->
   </style>

   <div id="backupcreator">
   <h1>
   Backup Creator<?php
        if ($title != "") {
            echo ": " . $title;
        }
?>
   </h1>

   <?php
    }
    function backupcreator_chdir()
    {
        global $backupcreator_plugin;
        global $backupcreator_cwd;
        global $backupcreator_dir;
        global $backupcreator_save;
        $backupcreator_cwd = getcwd();
        if ($backupcreator_plugin) {
            chdir($backupcreator_save);
        }
        $backupcreator_dir = getcwd();
    }
    function backupcreator_unchdir()
    {
        global $backupcreator_cwd;
        if ($backupcreator_cwd != "" && file_exists($backupcreator_cwd) && is_dir($backupcreator_cwd)) {
            chdir($backupcreator_cwd);
        }
    }
    function backupcreator_footer()
    {
?>
   </div>
   <?php
    }
    function backupcreator_welcome()
    {
        global $backupcreator_plugin;
        global $backupcreator_import;
        $backupcreator_name = get_bloginfo('name');
        $backupcreator_url  = get_bloginfo('url');
        backupcreator_chdir();
        $backupcreator_files = glob("*.zip");
        backupcreator_unchdir();
        if ($backupcreator_import == "") {
            $backupcreator_custom = "http://";
        } else {
            $backupcreator_custom = $backupcreator_import;
        }
?>
   <?php
        backupcreator_header();
?>

   <p>Welcome to <b>Backup Creator.</b> You can use this tool to create a backup this site. It will give you a zip file to download, which you can then install as a plugin onto any new WordPress blog, which will restore that backup.</p>

   <p><b>Choose your selection below:</b> either create a backup of this site, or choose which backup you would like to restore.</p>
   
   <p><b>Warning:</b> Restoring a backup will wipe ALL blog posts, settings, and data from this site and replace it with the restored backup file.</p>

   <form method="POST">
   <label><input type="radio" name="backupcreator_file" value="" onclick="document.getElementById('backupcreator_submit').value='Backup This Site'; backupcreator_hideFTP();" checked="checked" /> Backup This Site</label><br />

   <?php
        foreach ($backupcreator_files as $backupcreator_file):
?>
   <?php
            $backupcreator_file = basename($backupcreator_file);
?>

   <label><nobr><input type="radio" name="backupcreator_file" value="<?php
            echo $backupcreator_file;
?>" onclick="document.getElementById('backupcreator_submit').value='Restore From Backup'; backupcreator_showFTP();" /> <b>Restore From:</b></label> <a href="<?php
            echo backupcreator_download($backupcreator_file);
?>"><?php
            echo $backupcreator_file;
?></a> <small><b><a href="<?php
            echo backupcreator_download($backupcreator_file);
?>">(Download ZIP file)</a> <a title="backupcreator.zip" href="<?php
            echo backupcreator_installer($backupcreator_file);
?>">(Download WP plugin)</a></b></small></nobr><br />
   <?php
        endforeach;
?>
   <label onclick="document.getElementById('backupcreator_custom').focus(); backupcreator_showFTP();"><input type="radio" name="backupcreator_file" id="backupcreator_option_custom" value="custom" /> <b>Restore from URL:</b> (must be a BackupCreator zip file)</label><br /> 
   <textarea style="margin-left:25px;" name="backupcreator_custom" id="backupcreator_custom" onfocus="document.getElementById('backupcreator_option_custom').checked=true; document.getElementById('backupcreator_submit').value='Restore From Backup'" cols="50" rows="2"><?php
        echo $backupcreator_custom;
?></textarea><br />

   <?php
        if (!$backupcreator_plugin):
?><p align="center"><?php
        endif;
?>

   <input class="button-primary" type="submit" name="backupcreator_submit" id="backupcreator_submit" value="Backup This Site" onclick="if (this.value == 'Restore From Backup') { return confirm('Are you SURE you want to restore this BACKUP into this blog?\n\nWARNING: This will wipe the contents of the ENTIRE blog!'); } else { return confirm('Are you SURE you want to backup the site &quot;<?php
        echo $backupcreator_name;
?>&quot; (<?php
        echo $backupcreator_url;
?>)?'); }" /> 
   <input type="submit" class="button" name="backupcreator_deactivate" value="Deactivate License for This Site" onclick="return confirm('Are you SURE you want to deactivate your Backup Creator license for this site?');" />
   </form>
   
   <?php
        if (!$backupcreator_plugin):
?></p><?php
        endif;
?>

   <?php
    }
    function backupcreator_credentials()
    {
        global $wp_filesystem;
        $url    = "options-general.php?page=" . plugin_basename(__FILE__);
        $fields = array(
            "backupcreator_file",
            "backupcreator_submit",
            "backupcreator_custom"
        );
        if (false === ($creds = request_filesystem_credentials($url, '', false, false, $fields))) {
            return false;
        }
        return true;
    }
    function backupcreator_check()
    {
        global $backupcreator_plugin;
        global $wpdb;
        if (!$backupcreator_plugin && (!file_exists("wp-blog-header.php") || !file_exists("wp-config.php"))) {
            die("Place this file in your WordPress folder.");
        }
        if (exec("echo test") != "test") {
            die("Your web server does not support exec");
        }
        if (ini_get('safe_mode')) {
            die("Your web host is running in safe mode");
        }
        if (!current_user_can("manage_options")) {
            $login = get_option('siteurl') . '/wp-login.php?redirect_to=' . htmlentities(get_option('siteurl') . '/backupcreator.php');
            die('You need to login as the administrator of this blog before you continue. <a href="' . $login . '">Click here to login.</a>');
        }
    }
    function backupcreator_zip()
    {
        global $backupcreator_zipfile;
        global $backupcreator_plugin;
        global $backupcreator_save;
        $backupcreator_zipfile = trim($backupcreator_zipfile);
        $dir                   = dirname(WP_CONTENT_DIR);
        $curDir                = getcwd();
        chdir($dir);
        if (stristr(PHP_OS, 'WIN') && !(stristr(PHP_OS, 'Darwin'))) {
        } else {
            echo system('zip -r -q ' . escapeshellarg($backupcreator_save . "/" . $backupcreator_zipfile) . ' * -x "*error_log" "*backupcreator.*" "*.wpt" "*backup-*.zip" "*SimplePHPE*.php" "backupbuddy_backups"');
            chdir($backupcreator_save);
            echo system('zip -u -r -q ' . escapeshellarg($backupcreator_save . "/" . $backupcreator_zipfile) . ' * -i backupcreatorfile-*');
        }
        chdir($curDir);
        return $backupcreator_zipfile;
    }
    function backupcreator_unzip($file, $folder = ".")
    {
        global $backupcreator_dir;
        global $backupcreator_plugin;
        global $backupcreator_save;
        backupcreator_chdir();
        $file = basename($file);
        if (stristr(PHP_OS, 'WIN') && !(stristr(PHP_OS, 'Darwin'))) {
        } else {
            system("mkdir " . $backupcreator_save);
            system("mkdir " . $backupcreator_save . "/" . $folder);
            chmod($backupcreator_save . "/" . $folder, constant("BACKUPCREATOR_CHMOD"));
            backupcreator_msg("Unzipping " . $backupcreator_save . "/" . $folder . "/" . $file);
            backupcreator_msg(system("unzip -o -u -q '" . $backupcreator_save . "/" . $file . "' -d " . $folder));
        }
        backupcreator_unchdir();
    }
    function backupcreator_chmod()
    {
        global $backupcreator_save;
        if (!function_exists("posix_getpwuid")) {
            return;
        }
        $stat  = stat(dirname(WP_CONTENT_DIR));
        $pwuid = posix_getpwuid($stat['uid']);
        $chown = $pwuid["name"];
        @system("chown -R " . $chown . ":" . $chown . " " . $backupcreator_save);
        @chown($backupcreator_save, $stat["uid"]);
    }
    function backupcreator_getandsave($url, $fileTarget, $verbose = false)
    {
        global $backupcreator_save;
        if (!chmod($backupcreator_save, constant("BACKUPCREATOR_CHMOD"))) {
            chmod($backupcreator_save, 0666);
        }
        if (!touch($backupcreator_save)) {
            die("Please chmod the folder " . $folder);
        }
        backupcreator_save(backupcreator_socket($url), $fileTarget, $verbose);
    }
    function backupcreator_socket($url)
    {
        $r                = array(
            'method' => 'GET',
            'timeout' => 5,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'headers' => array(),
            'body' => null,
            'cookies' => array()
        );
        $arrURL           = parse_url($url);
        $fsockopen_host   = $arrURL['host'];
        $secure_transport = false;
        if (!isset($arrURL['port'])) {
            if (($arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https') && extension_loaded('openssl')) {
                $fsockopen_host   = "ssl://$fsockopen_host";
                $arrURL['port']   = 443;
                $secure_transport = true;
            } else {
                $arrURL['port'] = 80;
            }
        }
        if ('localhost' == strtolower($fsockopen_host)) {
            $fsockopen_host = '127.0.0.1';
        }
        $handle      = fsockopen($fsockopen_host, $arrURL['port']);
        $requestPath = $arrURL['path'] . (isset($arrURL['query']) ? '?' . $arrURL['query'] : '');
        $strHeaders  = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n";
        $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n";
        if (isset($r['user-agent'])) {
            $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n";
        }
        if (is_array($r['headers'])) {
            foreach ((array) $r['headers'] as $header => $headerValue) {
                $strHeaders .= $header . ': ' . $headerValue . "\r\n";
            }
        } else {
            $strHeaders .= $r['headers'];
        }
        $strHeaders .= "\r\n";
        if (!is_null($r['body'])) {
            $strHeaders .= $r['body'];
        }
        fwrite($handle, $strHeaders);
        return $handle;
    }
    function backupcreator_save($socket, $fileTarget, $verbose = false)
    {
        $packet         = 16384;
        $megabyte       = 1048576;
        $out            = '';
        $headerendfound = false;
        $fp             = fopen($fileTarget, 'w');
        $buffer         = '';
        $size           = 0;
        while (!feof($socket)) {
            if ($verbose && ($size % $megabyte) < ($oldSize % $megabyte)) {
                backupcreator_msg(". ", false);
                flush();
            }
            $out     = fgets($socket, $packet);
            $oldSize = $size;
            $size    = $size + strlen($out);
            if ($headerendfound) {
                fwrite($fp, $out);
            } else {
                $buffer .= $out;
                $headerend = strpos($buffer, "\r\n\r\n");
                if ($headerend !== false) {
                    $headerendfound = true;
                    fwrite($fp, substr($buffer, $headerend + 4));
                    $buffer = '';
                }
            }
        }
        fclose($fp);
        fclose($socket);
        echo backupcreator_msg(floor($size / $megabyte) . " MB");
        if ($size == 0) {
            die("Error: File not found. Please re-check your URL");
        }
    }
    function backupcreator_replace($find, $replace, $object)
    {
        if (is_serialized($object)) {
            return serialize(backupcreator_replace($find, $replace, unserialize($object)));
        } elseif (is_object($object)) {
            foreach ($object as $key => $value) {
                $object->$key = backupcreator_replace($find, $replace, $value);
            }
        } elseif (is_array($object)) {
            foreach ($object as $key => $value) {
                $object[$key] = backupcreator_replace($find, $replace, $value);
            }
        } elseif (is_string($object)) {
            return str_replace($find, $replace, $object);
        }
        return $object;
    }
    function backupcreator_links($links, $file)
    {
        if ($file == plugin_basename(__FILE__)) {
            array_unshift($links, "<a href=\"options-general.php?page=$file\">Settings</a>");
        }
        return $links;
    }
    function backupcreator_setup_menu()
    {
        if (!current_user_can('update_plugins')) {
            return;
        }
        if (isset($_POST["backupcreator_deactivate"])) {
            backupcreator_deactivate();
        }
        add_options_page('Backup Creator Settings', 'Backup Creator', 10, __FILE__, "backupcreator_menu");
    }
    function backupcreator_menu()
    {
     /*
		$call = backupcreator_call();
        if (empty($call) || $call == "FAILED" || $call == "CANCELLED" || $call == "UNREGISTERED" || $call == "FAILED") {
            backupcreator_register($call);
            return;
        }
	*/	
?>
      <div class="wrap">
      <?php
        backupcreator_check();
        if (isset($_POST["backupcreator_file"]) && isset($_POST["backupcreator_submit"])) {
            $backupcreator_file = basename($_POST["backupcreator_file"]);
            if ($backupcreator_file == "") {
                backupcreator_backup();
            } else {
                backupcreator_restore($backupcreator_file);
            }
        } else {
            backupcreator_welcome();
        }
?>
      </div>
      <?php
    }
    function backupcreator_installer($link)
    {
        global $backupcreator_plugin;
        if ($backupcreator_plugin) {
            return dirname(WP_CONTENT_URL) . "/?backupcreator_download=" . rawurlencode($link);
        } else {
            return "backupcreator.php?backupcreator_download=" . rawurlencode($link);
        }
    }
    function backupcreator_download($link)
    {
        global $backupcreator_plugin;
        global $backupcreator_url;
        if ($backupcreator_plugin) {
            return $backupcreator_url . "/" . basename($link);
        } else {
            return "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["SCRIPT_NAME"]) . "/" . basename($link);
        }
    }
    function backupcreator_backup()
    {
        global $backupcreator_filesql, $backupcreator_htaccess, $backupcreator_sourceurl, $backupcreator_tableprefix, $backupcreator_zipfile;
        global $table_prefix;
        global $backupcreator_plugin;
        if ($table_prefix == '') {
            $table_prefix = 'wp_';
        }
        if (!defined("DB_HOST") || !defined("DB_USER") || !defined("DB_PASSWORD") || !defined("DB_NAME")) {
            die("There was an error loading your WordPress files.");
        }
        $dumpcommand = "mysqldump --opt --host=" . escapeshellarg(constant("DB_HOST")) . " --user=" . escapeshellarg(constant("DB_USER")) . " --password=" . escapeshellarg(constant("DB_PASSWORD")) . " " . escapeshellarg(constant("DB_NAME")) . " > " . $backupcreator_filesql;
        system($dumpcommand);
        if (!file_exists($backupcreator_filesql) || filesize($backupcreator_filesql) == 0) {
            die("There was an error backing up your WordPress database: " . $dumpcommand);
        }
        @copy(dirname(WP_CONTENT_DIR) . "/wp-config.php", $backupcreator_save . "/wp-config.php.new");
        @copy(dirname(WP_CONTENT_DIR) . "/.htaccess", $backupcreator_htaccess);
        backupcreator_msg("Copying " . dirname(WP_CONTENT_DIR) . "/.htaccess" . "into " . $backupcreator_htaccess);
        file_put_contents($backupcreator_sourceurl, get_bloginfo('url'));
        file_put_contents($backupcreator_tableprefix, $table_prefix);
        backupcreator_zip();
        backupcreator_chdir();
        @unlink("wp-config.php.new");
        @unlink("htaccess.new");
        @unlink($backupcreator_sourceurl);
        @unlink($backupcreator_filesql);
        @unlink($backupcreator_tableprefix);
        backupcreator_unchdir();
        $self = "options-general.php?page=" . plugin_basename(__FILE__);
?>
      <?php
        backupcreator_header("Backup Complete");
?>

      <?php
        if ($backupcreator_plugin):
?><p><?php
        else:
?><p align="center"><?php
        endif;
?>Your files are now backed up.</p>

      <h3>Point &amp; Click Restore (Recommended)</h3>

      <?php
        if ($backupcreator_plugin):
?><p><?php
        else:
?><p align="center"><?php
        endif;
?>If you would like to restore this backup onto another WordPress blog, just download the: <b><a href="<?php
        echo backupcreator_installer($backupcreator_zipfile);
?>">Backup Creator Plugin</a></b></p>

      <?php
        if ($backupcreator_plugin):
?><p><?php
        else:
?><p align="center"><?php
        endif;
?>Login to the WordPress dashboard of the &quot;new&quot; blog where you want to restore this backup.</p>

      <?php
        if ($backupcreator_plugin):
?><p><?php
        else:
?><p align="center"><?php
        endif;
?>Go to <code>Plugins, Add New</code> then click the <code>Upload</code> tab. Upload that <a href="<?php
        echo backupcreator_installer($backupcreator_zipfile);
?>">Backup Creator plugin</a>, choose &quot;<code>Restore from URL</code>&quot; and the URL of THIS blog's most recent backup is already hardcoded in.</p>

      <h3>Manual Restore (Alternative)</h3>
      <?php
        if ($backupcreator_plugin):
?><p><?php
        else:
?><p align="center"><?php
        endif;
?>You can manually restore your backup to this blog or any other WordPress blog by placing this zip file in the WordPress folder:<br />
      <b><a href="<?php
        echo backupcreator_download($backupcreator_zipfile);
?>"><?php
        echo backupcreator_download($backupcreator_zipfile);
?></a></b></p>

      <?php
        if ($backupcreator_plugin):
?><p><?php
        else:
?><p align="center"><?php
        endif;
?>Then install this &quot;<a href="<?php
        echo backupcreator_installer($backupcreator_zipfile);
?>">backupcreator.zip</a>&quot; file as a plugin and choose to restore the zip file.</p>

      <h3><a href="<?php
        echo $self;
?>">Return to Backup Creator</a></h3>

      <?php
        backupcreator_footer();
    }
    function backupcreator_msg($text, $lineBreak = true)
    {
        echo $text;
        if ($lineBreak) {
            echo "<br />\n";
        }
        flush();
    }
    function backupcreator_buffer()
    {
        for ($i = 0; $i < 1000; $i++) {
            echo '<!-- buffer -->' . "\n";
        }
        flush();
    }
    function backupcreator_permissions()
    {
        global $wp_filesystem;
        $url = "options-general.php?page=" . plugin_basename(__FILE__);
        if (false === ($creds = request_filesystem_credentials($url, '', false, false, null))) {
            return false;
        }
        if (!WP_Filesystem($creds)) {
            request_filesystem_credentials($url, '', true, false, null);
            return false;
        }
        $wp_filesystem->chmod($wp_filesystem->abspath(), constant("BACKUPCREATOR_CHMOD"), true);
        if (!@touch(dirname(WP_CONTENT_DIR) . "/backupcreator-touch")) {
            die("Please chmod your WordPress folder to 755.");
        }
        @unlink(dirname(WP_CONTENT_DIR) . "/backupcreator-touch");
    }
    function backupcreator_restore($backupcreator_file = "")
    {
        global $backupcreator_save;
        global $backupcreator_filesql, $backupcreator_htaccess, $backupcreator_sourceurl, $backupcreator_tableprefix, $backupcreator_zipfile;
        global $table_prefix;
        global $backupcreator_dir;
        global $backupcreator_chown;
        global $wpdb;
        global $wp_filesystem;
        echo "file = " . $backupcreator_save . "/" . $backupcreator_file;
        $credentials = backupcreator_credentials();
        if (!$credentials) {
            return false;
        }
        backupcreator_buffer();
        backupcreator_msg("Beginning restore process.");
        if (isset($_POST["backupcreator_custom"]) && $_POST["backupcreator_custom"] != "http://") {
            $url = $_POST["backupcreator_custom"];
            if (!preg_match('@^https?://@si', $url)) {
                die("Need to specify a FULL URL including the HTTP.");
            }
            if (!preg_match('@\.zip$@si', $url)) {
                die("Need to retrieve a zip file.");
            }
            backupcreator_msg("Loading " . $url);
            backupcreator_chdir();
            backupcreator_getandsave($url, $backupcreator_save . "/" . basename($url), true);
            backupcreator_unchdir();
            backupcreator_msg("Saved " . $url);
            $backupcreator_file = basename($url);
        }
        if (file_exists($backupcreator_save . "/" . $backupcreator_file)) {
            backupcreator_permissions();
            backupcreator_msg("Found restore file.");
            $backupcreator_blogname        = get_bloginfo('name');
            $backupcreator_blogdescription = get_bloginfo('url');
            $backupcreator_site            = get_bloginfo('url');
            $backupcreator_home            = get_bloginfo('home');
            backupcreator_msg("Unzipping " . $backupcreator_file);
            backupcreator_chdir();
            backupcreator_unzip($backupcreator_file, "backupcreator-new");
            backupcreator_chmod();
            $backupcreator_filesql     = (file_exists($backupcreator_save . "/backupcreator-new/wptwinfile-sql")) ? $backupcreator_save . "/backupcreator-new/wptwinfile-sql" : $backupcreator_save . "/backupcreator-new/backupcreatorfile-sql";
            $backupcreator_tableprefix = (file_exists($backupcreator_save . "/backupcreator-new/wptwinfile-tableprefix")) ? $backupcreator_save . "/backupcreator-new/wptwinfile-tableprefix" : $backupcreator_save . "/backupcreator-new/backupcreatorfile-tableprefix";
            $backupcreator_sourceurl   = (file_exists($backupcreator_save . "/backupcreator-new/wptwinfile-sourceurl")) ? $backupcreator_save . "/backupcreator-new/wptwinfile-sourceurl" : $backupcreator_save . "/backupcreator-new/backupcreatorfile-sourceurl";
            $backupcreator_htaccess    = (file_exists($backupcreator_save . "/backupcreator-new/wptwinfile-htaccess")) ? $backupcreator_save . "/backupcreator-new/wptwinfile-htaccess" : $backupcreator_save . "/backupcreator-new/backupcreatorfile-htaccess";
            $backupcreator_oldpath     = (file_exists($backupcreator_save . "/backupcreator-new/wptwinfile-oldpath")) ? $backupcreator_save . "/backupcreator-new/wptwinfile-oldpath" : $backupcreator_save . "/backupcreator-new/backupcreatorfile-oldpath";
            backupcreator_unchdir();
            backupcreator_msg("Done unzipping.");
            backupcreator_chdir();
            if (!file_exists($backupcreator_tableprefix)) {
                die($backupcreator_tableprefix . ": file does not exist.");
            }
            $backupcreator_prefix = trim(file_get_contents($backupcreator_tableprefix));
            backupcreator_msg("Table prefix: " . $backupcreator_prefix);
            if (!file_exists($backupcreator_save . "/backupcreator-new/wp-config.php")) {
                die("Config file in restore zip file does not exist.");
            }
            @chmod($backupcreator_save . "/backupcreator-new/wp-config.php", constant("BACKUPCREATOR_CHMOD"));
            @system("chmod " . "0" . decoct(constant("BACKUPCREATOR_CHMOD")) . " " . $backupcreator_save . "/backupcreator-new/wp-config.php");
            if (!is_writable($backupcreator_save . "/backupcreator-new/wp-config.php")) {
                die("Cannot write to configuration file.");
            }
            if (strpos($backupcreator_prefix, '_') !== FALSE) {
                $backupcreator_configFile = file_get_contents($backupcreator_save . "/backupcreator-new/wp-config.php");
                $backupcreator_configFile = str_replace($backupcreator_prefix, $table_prefix, $backupcreator_configFile);
                $backupcreator_configFile = preg_replace("@(define\('DB\_NAME', ')(.*?)('\);)@i", '$1' . constant("DB_NAME") . '$3', $backupcreator_configFile);
                $backupcreator_configFile = preg_replace("@(define\('DB\_USER', ')(.*?)('\);)@i", '$1' . constant("DB_USER") . '$3', $backupcreator_configFile);
                $backupcreator_configFile = preg_replace("@(define\('DB\_" . chr(80) . chr(65) . chr(83) . chr(83) . chr(87) . chr(79) . chr(82) . chr(68) . "', ')(.*?)('\);)@i", "define('DB_" . chr(80) . chr(65) . chr(83) . chr(83) . chr(87) . chr(79) . chr(82) . chr(68) . "', '" . constant("DB_PASSWORD") . '$3', $backupcreator_configFile);
                $backupcreator_configFile = preg_replace("@(define\('DB\_HOST', ')(.*?)('\);)@i", '$1' . constant("DB_HOST") . '$3', $backupcreator_configFile);
                file_put_contents($backupcreator_save . "/backupcreator-new/wp-config.php", $backupcreator_configFile);
            }
            backupcreator_msg("Repairing htaccess file.");
            $backupcreator_backupurl   = trim(file_get_contents($backupcreator_sourceurl));
            $backupcreator_backuppath  = parse_url($backupcreator_backupurl, PHP_URL_PATH);
            $backupcreator_restoreurl  = $backupcreator_site;
            $backupcreator_restorepath = parse_url($backupcreator_site, PHP_URL_PATH);
            $htaccessWriter = fopen($backupcreator_save . "/backupcreator-new/backupcreatorfile-htaccessnew", 'w') or die("Cannot write new htaccess file");
            foreach (file($backupcreator_htaccess) as $htaccessLine) {
                if ($backupcreator_backuppath != "" && $backupcreator_backuppath != "/" && $backupcreator_restorepath != "" && $backupcreator_restorepath != "/") {
                    $htaccessLine = str_replace($backupcreator_backuppath, $backupcreator_restorepath, $htaccessLine);
                    $htaccessLine = str_replace($backupcreator_sourceurl, $backupcreator_site, $htaccessLine);
                } elseif ($backupcreator_backuppath != "" && $backupcreator_backuppath != "/" && ($backupcreator_restorepath == "" || $backupcreator_restorepath == "/")) {
                    $htaccessLine = str_replace($backupcreator_site, '', $htaccessLine);
                    $htaccessLine = str_replace($backupcreator_backuppath, '', $htaccessLine);
                } elseif (($backupcreator_backuppath == "" || $backupcreator_backuppath == "/") && $backupcreator_restorepath != "" && $backupcreator_restorepath != "/") {
                    $htaccessLine = str_replace('RewriteBase /', 'RewriteBase ' . $backupcreator_restorepath . '/', $htaccessLine);
                    $htaccessLine = str_replace('RewriteRule . /', 'RewriteRule . ' . $backupcreator_restorepath . '/', $htaccessLine);
                }
                fwrite($htaccessWriter, $htaccessLine);
            }
            fclose($htaccessWriter);
            backupcreator_msg("Repairing sitemap files.");
            if (file_exists($backupcreator_save . "/backupcreator-new/sitemap.xml")) {
                $sitemapWriter = fopen($backupcreator_save . '/backupcreator-new/sitemap.xml', 'w');
                foreach (file($backupcreator_save . "/backupcreator-new/sitemap.xml") as $sitemapLine) {
                    $sitemapLine = str_replace($backupcreator_sourceurl, $backupcreator_site, $sitemapLine);
                    fwrite($sitemapWriter, $htaccessLine);
                }
                fclose($sitemapWriter);
                if (file_exists($backupcreator_save . "/backupcreator-new/sitemap.xml.gz")) {
                    @unlink($backupcreator_save . "/backupcreator-new/sitemap.xml.gz");
                    system("gzip -c " . $backupcreator_save . "/backupcreator-new/sitemap.xml > " . $backupcreator_save . "/backupcreator-new/sitemap.xml.gz");
                }
            }
            backupcreator_msg("Deleting old database.");
            if ($table_prefix == '') {
                $table_prefix = 'wp_';
            }
            $prefix = str_replace('_', '\_', $table_prefix);
            if ($prefix != "" && $prefix != "_") {
                $backupcreator_tables = $wpdb->get_col("SHOW TABLES LIKE '" . $prefix . "%'");
                foreach ($backupcreator_tables as $backupcreator_table) {
                    $wpdb->query("DROP TABLE " . $backupcreator_table);
                }
            }
            backupcreator_msg("Importing new database.");
            system("mysql --user='" . escapeshellarg(constant("DB_USER")) . "' --password='" . escapeshellarg(constant("DB_PASSWORD")) . "' " . escapeshellarg(constant("DB_NAME")) . " < " . $backupcreator_filesql);
            backupcreator_msg("Repairing new database.");
            $backupcreator_wpdb = new wpdb(constant("DB_USER"), constant("DB_PASSWORD"), constant("DB_NAME"), constant("DB_HOST")) or die("Could not connect to database");
            backupcreator_unchdir();
            $backupcreator_wpdb->query("UPDATE " . $table_prefix . "options SET option_value='" . $backupcreator_wpdb->escape($backupcreator_blogname) . "' WHERE option_name='blogname' LIMIT 1");
            $backupcreator_wpdb->query("UPDATE " . $table_prefix . "options SET option_value='" . $backupcreator_wpdb->escape($backupcreator_blogdescription) . "' WHERE option_name='blogdescription' LIMIT 1");
            $backupcreator_wpdb->query("UPDATE " . $table_prefix . "options SET option_value='" . $backupcreator_wpdb->escape($backupcreator_site) . "' WHERE option_name='siteurl' LIMIT 1");
            $backupcreator_wpdb->query("UPDATE " . $table_prefix . "options SET option_value='" . $backupcreator_wpdb->escape($backupcreator_home) . "' WHERE option_name='home' LIMIT 1");
            $backupcreator_tables = $wpdb->get_col("SHOW TABLES LIKE '" . $prefix . "%'");
            $backupcreator_wpdb->query("SET session wait_timeout=600");
            foreach ($backupcreator_tables as $table) {
                $rows = $backupcreator_wpdb->get_results("SELECT * FROM " . $table);
                foreach ($rows as $row) {
                    $update = array();
                    foreach ($row as $colName => $colValue) {
                        $newValue = backupcreator_replace($backupcreator_backupurl, $backupcreator_restoreurl, $colValue);
                        $update[] = $colName . " = '" . $newValue . "'";
                    }
                    if (count($update) > 0) {
                        $update = implode(", ", $update);
                        $backupcreator_wpdb->query("UPDATE " . $table . " SET " . $update);
                    }
                }
            }
            $blog_folder = dirname(WP_CONTENT_DIR);
            system("rm -rf " . $blog_folder . "/*.* " . $blog_folder . "/wp-admin ." . $blog_folder . "/wp-content " . $blog_folder . "/wp-includes");
            system("cp -rf " . $backupcreator_save . "/backupcreator-new/* " . $blog_folder);
            system("cp -f " . $blog_folder . "/backupcreatorfile-htaccessnew " . $blog_folder . "/.htaccess");
            system("rm -rf " . $blog_folder . "/backupcreatorfile-*");
            system("rm -rf " . $backupcreator_save . "/backupcreatorfile-*");
            system("rm -rf " . $backupcreator_save . "/backupcreator-new/backupcreatorfile-*");
            backupcreator_msg("Restoration complete!");
            echo '<a target="_blank" href="' . $backupcreator_site . '">Visit Your Restored Blog Now</a>';
        }
    }
}
if (!$backupcreator_plugin) {
    if (!file_exists(dirname(__FILE__) . '/wp-config.php')) {
        die("Could not locate WordPress.");
    }
    if (!defined("ABSPATH")) {
        require_once(dirname(__FILE__) . '/wp-config.php');
    }
    $wp->init();
    $wp->parse_request();
    $wp->query_posts();
    $wp->register_globals();
    ob_implicit_flush(true);
    backupcreator_check();
    $oldDir = getcwd();
    chdir(dirname(__FILE__));
}
if (!$backupcreator_plugin && isset($_POST["backupcreator_submit"])) {
    $backupcreator_file = basename($_POST["backupcreator_file"]);
    if ($backupcreator_file == "") {
        backupcreator_backup();
    } else {
        backupcreator_restore($backupcreator_file);
    }
} elseif ($backupcreator_plugin) {
    add_filter("plugin_action_links", "backupcreator_links", 10, 2);
    add_action('admin_menu', "backupcreator_setup_menu");
    add_action('init', "backupcreator_init");
} else {
    die("Please run this file as a plugin by creating a new WordPress blog, login to your Dashboard, go to Plugins, Add New, Upload, upload the zip file, then Activate Plugin. Then you can go to Settings, Backup Creator to restore your backup.");
    backupcreator_header();
    backupcreator_welcome();
    backupcreator_footer();
}
if (!$backupcreator_plugin) {
    chdir($oldDir);
}
?>
