<?php
/*
dv at josheli.com

What it does: 
It will backup all accounts under a reseller using cURL, optionally over SSL.

How it works:
Reads all accounts (domain and username specifically) from the listaccts page in WHM
Creates filenames like "bkup_clientdomain_com_11_11_03.tar.gz"
Uses cUrl over SSL to call the getbackup script of cpanel for each account, using the
account's username and the reseller's password

This script doesn't require cron, but i use it. Cron for Windows: 
http://www.kalab.com/freeware/cron/cron.htm 

Instructions:
1. Make sure you have the curl extension for PHP available
2. Modify "config" variables below, to suit
3. From the command prompt:
    >php bkup_curl.php
4. ([Or] Optionally) Set up a cron job to call this script

Notes: 
*This script could easily be run from the server (but why backup a site on its own server); running it from another server is a pretty good option though.
*Doesn't do well with sites over about 35mb :(
*Remember that you will be using the sub-accounts' bandwidth
*My firewall needed to be configured to allow PHP to access the internet.
*I'm using the PHP 5 beta 2 cli.

*/

/*** BEGIN CONFIG ***/

$reseller 'www.mydomain.com';//your reseller url
$whmUser 'username';//your web host manager user name
$whmPass 'password';//your web host manager password
$sleep 0;//how many seconds to pause between downloads (be nice to your shared server friends :)
$bkUpReseller true;//backup the reseller account also? (it's not in the listaccts page)
$backupPath '.\\backups';//path to directory where you want to save your backups
$logEchoNone 'echo';//write a log to 'log' or 'echo' or 'none'(no log)
$logFileName 'bkup_log.txt';//can include a path too; only makes sense if $logEchoNone = 'log'
$useSsl false;

/*** END CONFIG ***/


/*** BEGIN FUNCTIONS ***/

function getByCurl($url$user ''$pass '') {
    global 
$useSsl;

    
$ch curl_init(); 
    
//tells curl to save result in a variable instead of outputing to page
    
curl_setopt($chCURLOPT_RETURNTRANSFER1);
    
curl_setopt($chCURLOPT_URL$url);  
    
curl_setopt($chCURLOPT_USERPWD"$user:$pass");
  if(
$useSsl){
      
curl_setopt ($chCURLOPT_SSL_VERIFYPEER0);
      
curl_setopt ($chCURLOPT_SSL_VERIFYHOST0);
  }
    
$result curl_exec($ch);
    
curl_close($ch);

    return 
$result;
}

function 
saveBackup(&$backup$fileName$path) {

  global 
$totalSize;

    if(!
is_dir($path)){
    
writeLog("Creating backup directory $path...\n");
        if(!
mkdir($path)){
            
writeLog("Could not create backup directory: $path.\n");
            return 
false;
        }
    }
    
$path realpath($path);
    if(
substr($pathstrlen($path)-1strlen($path) )!== '\\') {
        
$path .= '\\';
    }
    
$filePath $path.$fileName;
    
$fp fopen($filePath,'wb');
    if((
$len fwrite($fp$backup))===false){
        
writeLog("Could not backup $fileName to $path.\n");
        return;
    }
    else {
    
$totalSize += $len;
        
writeLog("Backed up $len bytes to $path$fileName.\n");
    }

    
fclose($fp);
    return;
}

function 
writeLog($entry) {
    global 
$logEchoNone,$logFileName;

  
$method strtolower($logEchoNone);
  
    if(
$method == 'log') {
        
$fp fopen($logFileName,'ab');
    }
    elseif(
$method == 'echo') {
        
$fp STDOUT;
    }
  else {
      return;
  }
        
    
$entry date('r').' - '.$entry;
    
    
fwrite($fp$entry);

    if(
$method == 'log')
        
fclose($fp);

    return;
}

function 
getMicroTime(){ 
  list(
$usec$sec) = explode(" ",microtime()); 
  return ((float)
$usec + (float)$sec); 


set_time_limit(0);
$time_start getMicroTime();

if (!
extension_loaded('curl')) {
  
dl('php_curl.' .PHP_SHLIB_SUFFIX) or die("Could not load curl extension");
}
if(
$useSsl) {
  
$protocol 'https://';
  
$cpPort '2083';
  
$whmPort '2087';
  
writeLog("Using SSL.\n");
}
else {
  
$protocol 'http://';
  
$cpPort '2082';
  
$whmPort '2086';
  
writeLog("Not using SSL.\n");

$totalSize 0;

//get the WHM 'list accounts' page
writeLog("Retrieving WHM accounts page...\n");
$acctsPage getByCurl("$protocol$reseller:$whmPort/scripts2/listaccts?viewall=1",$whmUser,$whmPass);
//get each accounts table row
$int2 preg_match_all("/<tr class=(?:tdshade2|tdshade1)>(.*?)<\/tr>/is"$acctsPage$matches);

if(
$int2 && is_array($matches[1])) { 
  foreach(
$matches[1] as $match) {

      
$account = array();
        
$fileName '';
        
$siteBackup '';

    
$account explode('</td><td>',$match);
    
$account[0] = strip_tags(trim($account[0]));//domain
    
$account[2] = strip_tags(trim($account[2]));//username
        
    
$fileName 'bkup_'.str_replace('.','_',$account[0]).'_'.date('n_j_y').'.tar.gz';

        
writeLog("Retrieving $fileName...\n");
        
$siteBackup getByCurl("$protocol$reseller:$cpPort/getbackup/$fileName",$account[2],$whmPass);
        
writeLog("Saving $fileName to $backupPath...\n");
    
saveBackup($siteBackup$fileName$backupPath);
                            
    
sleep($sleep);
  }
}

if(
$bkUpReseller){
  
$fileName '';
  
$siteBackup '';
  
$fileName 'bkup_'.str_replace('.','_',$reseller).'_'.date('n_j_y').'.tar.gz';
    
writeLog("Retrieving $fileName...\n");
    
$siteBackup getByCurl("$protocol$reseller:$cpPort/getbackup/$fileName",$whmUser,$whmPass);
    
writeLog("Saving $fileName to $backupPath...\n");
  
saveBackup($siteBackup$fileName$backupPath);


$time_end getMicroTime();
$time $time_end $time_start;

$totalKb round($totalSize/1024,2);
writeLog("Backed up $totalKb KB.\n");
writeLog("Elapsed time: ".round($time,2)." seconds.\n");

?>