private function init_connection()
 {
     // Verify authentication information
     try {
         $this->auth = new CF_Authentication($this->username, $this->api_key);
         $this->auth->authenticate();
     } catch (Exception $e) {
         throw new moodle_exception('repo_auth_fail', 'repository_rackspace_cf');
     }
     // Initialize the connection
     $conn = new CF_Connection($this->auth);
     // Get a list of all the available containers
     $containers = $conn->list_containers();
     // See if the container already exists
     $container_exists = in_array($this->container_name, $containers);
     if ($container_exists) {
         // Save a connection to the container
         $this->container = $conn->get_container($this->container_name);
     } else {
         // The container specified does not exists so create it.
         $this->container = $conn->create_container($this->container_name);
     }
     if ($this->cdn_enable) {
         // Enable CDN for the container
         $this->container->make_public();
     } else {
         // Disable CDN for the container
         $this->container->make_private();
     }
 }
function doRackspaceUploadNewDeleteOld($RS_USERNAME, $RS_KEY)
{
    //get the most recent grouping of files.
    $arrRecentFiles = getMostRecentFiles();
    sort($arrRecentFiles);
    if (count($arrRecentFiles > 0)) {
        //============================================ get our rackspace auth, connection, and container set up =====================================
        //Create the authentication instance
        $auth = new CF_Authentication($RS_USERNAME, $RS_KEY);
        //Perform authentication request
        $auth->authenticate();
        //Create a connection to the storage/cdn system(s) and pass in the validated CF_Authentication instance.
        $conn = new CF_Connection($auth);
        //get the "salesforce_backups" container
        $cont = $conn->get_container('salesforce_backups');
        //============================================ end get our rackspace auth, connection, and container set up =====================================
        //get the date prefix off of the most recent grouping of local files
        $recentFileDate = getDatePrefix($arrRecentFiles[0]);
        //get the listing of files from rackspace cloud files
        $arrRackspaceFiles = $cont->list_objects();
        sort($arrRackspaceFiles);
        //get a distinct listing off all the rackspace prefixes (Dates)
        $arrRackspaceDistinctPrefixes = filterDistinctPrefixes($arrRackspaceFiles);
        //see if the most recent local date is in rackspace or not
        if (!in_array($recentFileDate, $arrRackspaceDistinctPrefixes)) {
            //we haven't uploaded our most recent local files yet to rackspace.  Let's do it.
            uploadToRackspace($cont, $arrRecentFiles);
        }
        //refresh our container and objects so we are sure the newly included files are in them
        $cont = $conn->get_container('salesforce_backups');
        //if we have more than 4 distinct date range prefixes (more than 4 weekly backups), delete the older ones so we are just left with the 4 most recent.
        deleteOlderBackups($conn, $cont);
    }
}
Beispiel #3
0
/**
 * Get the Swift thumbnail container for this wiki.
 *
 * @param $site string
 * @param $lang string
 * @param $relPath string Path relative to container
 * @return CF_Container|null
 */
function wmfGetSwiftThumbContainer($site, $lang, $relPath)
{
    global $wmfSwiftConfig;
    // from PrivateSettings.php
    $auth = new CF_Authentication($wmfSwiftConfig['user'], $wmfSwiftConfig['key'], NULL, $wmfSwiftConfig['authUrl']);
    try {
        $auth->authenticate();
    } catch (Exception $e) {
        wfDebugLog('swiftThumb', "Could not establish a connection to Swift.");
        return null;
    }
    $conn = new CF_Connection($auth);
    $wikiId = "{$site}-{$lang}";
    // Get the full swift container name, including any shard suffix
    $name = "{$wikiId}-local-thumb";
    if (in_array($wikiId, array('wikipedia-commons', 'wikipedia-en'))) {
        // Code stolen from FileBackend::getContainerShard()
        if (preg_match("!^(?:[^/]{2,}/)*[0-9a-f]/(?P<shard>[0-9a-f]{2})(?:/|\$)!", $relPath, $m)) {
            $name .= '.' . $m['shard'];
        } else {
            throw new MWException("Can't determine shard of path '{$relPath}' for '{$wikiId}'.");
        }
    }
    try {
        $container = $conn->get_container($name);
    } catch (NoSuchContainerException $e) {
        // container not created yet
        $container = null;
        wfDebugLog('swiftThumb', "Could not access `{$name}`; container does not exist.");
    }
    return $container;
}
Beispiel #4
0
 protected function initContainer()
 {
     if (!$this->containerInitiated) {
         $auth = new \CF_Authentication($this->username, $this->apiKey);
         $auth->authenticate();
         $conn = new \CF_Connection($auth, $this->serviceNet);
         $container = $conn->get_container($this->name);
         parent::__construct($container->cfs_auth, $container->cfs_http, $container->name, $container->object_count, $container->bytes_used);
     }
     $this->containerInitiated = true;
 }
 private static function getBucket($bucketName)
 {
     $auth = self::getAuth();
     $conn = new CF_Connection($auth);
     try {
         $images = $conn->get_container($bucketName);
     } catch (NoSuchContainerException $e) {
         $images = $conn->create_container($bucketName);
         $uri = $images->make_public();
     }
     return $images;
 }
Beispiel #6
0
 /**
  * Creates container
  *
  * @param string $container_id
  * @param string $error
  * @return boolean
  */
 function create_container(&$container_id, &$error)
 {
     if (!$this->_init($error)) {
         return false;
     }
     try {
         $containers = $this->_connection->list_containers();
     } catch (Exception $exception) {
         $error = sprintf('Unable to list containers (%s).', $exception->getMessage());
         return false;
     }
     if (in_array($this->_config['container'], (array) $containers)) {
         $error = sprintf('Container already exists: %s.', $this->_config['container']);
         return false;
     }
     try {
         $container = $this->_connection->create_container($this->_config['container']);
         $container->make_public();
     } catch (Exception $exception) {
         $error = sprintf('Unable to create container: %s (%s).', $this->_config['container'], $exception->getMessage());
         return false;
     }
     $matches = null;
     if (preg_match('~^https?://(.+)$~', $container->cdn_uri, $matches)) {
         $container_id = $matches[1];
     }
     return true;
 }
 /**
  * Get a connection to the Swift proxy
  *
  * @return CF_Connection|false
  * @throws InvalidResponseException
  */
 protected function getConnection()
 {
     if ($this->conn === false) {
         throw new InvalidResponseException();
         // failed last attempt
     }
     // Session keys expire after a while, so we renew them periodically
     if ($this->conn && time() - $this->connStarted > $this->authTTL) {
         $this->conn->close();
         // close active cURL connections
         $this->conn = null;
     }
     // Authenticate with proxy and get a session key...
     if ($this->conn === null) {
         $this->connContainers = array();
         try {
             $this->auth->authenticate();
             $this->conn = new CF_Connection($this->auth);
             $this->connStarted = time();
         } catch (AuthenticationException $e) {
             $this->conn = false;
             // don't keep re-trying
         } catch (InvalidResponseException $e) {
             $this->conn = false;
             // don't keep re-trying
         }
     }
     if (!$this->conn) {
         throw new InvalidResponseException();
         // auth/connection problem
     }
     return $this->conn;
 }
 public function createSynchronizer()
 {
     $username = sfConfig::get('app_rackspace_username');
     $key = sfConfig::get('app_rackspace_key');
     $containerName = sfConfig::get('app_rackspace_container');
     $webDir = sfConfig::get('sf_web_dir');
     $ttl = sfConfig::get('app_rackspace_ttl');
     $mimeTypeResolver = $this->get('mime_type_resolver');
     $dispatcher = $this->get('dispatcher');
     $this->logSection("rackspace", "Connecting '{$username}' to '{$containerName}'");
     $auth = new CF_Authentication($username, $key);
     $auth->authenticate();
     $conn = new CF_Connection($auth);
     $container = $conn->create_container($containerName);
     $synchronizer = new knpDmRackspaceSynchronizer($container, $webDir, $ttl, $mimeTypeResolver, $dispatcher);
     return $synchronizer;
 }
 protected function createSynchronizer()
 {
     require_once dirname(__FILE__) . '/../vendor/rackspace/cloudfiles.php';
     $username = sfConfig::get('app_rackspace_username');
     $key = sfConfig::get('app_rackspace_key');
     $containerName = sfConfig::get('app_rackspace_container');
     $webDir = sfConfig::get('sf_web_dir');
     $ttl = sfConfig::get('app_rackspace_ttl');
     $mimeTypeResolver = $this->container->getService('mime_type_resolver');
     $dispatcher = $this->container->getService('dispatcher');
     $auth = new CF_Authentication($username, $key);
     $auth->authenticate();
     $conn = new CF_Connection($auth);
     $container = $conn->create_container($containerName);
     $synchronizer = new knpDmRackspaceSynchronizer($container, $webDir, $ttl, $mimeTypeResolver, $dispatcher);
     return $synchronizer;
 }
	/**
	 * Close the connection to the Swift proxy
	 *
	 * @return void
	 */
	protected function closeConnection() {
		if ( $this->conn ) {
			$this->conn->close(); // close active cURL handles in CF_Http object
			$this->conn = null;
			$this->sessionStarted = 0;
			$this->connContainerCache->clear();
		}
	}
Beispiel #11
0
 /**
  * Close the connection to the Swift proxy
  *
  * @return void
  */
 protected function closeConnection()
 {
     if ($this->conn) {
         $this->srvCache->delete($this->getCredsCacheKey($this->auth->username));
         $this->conn->close();
         // close active cURL handles in CF_Http object
         $this->conn = null;
         $this->connStarted = 0;
     }
 }
 /**
  * Set up Rackspace cloud files - used by rackspace:initialise task as well as constructor
  * 
  * @see rackspaceInitialiseTask::execute()
  * @var array $options    Passed through from __construct
  * @return CF_Container
  */
 public static function setup($options)
 {
     $required_fields = array('container', 'api_key', 'username');
     $adapter_options = $options['options'];
     foreach ($required_fields as $f) {
         if (!array_key_exists($f, $adapter_options)) {
             throw new InvalidArgumentException(sprintf("Missing option '%s' is required", $f));
         }
     }
     $adapter_options = array_merge(self::$adapter_options, $adapter_options);
     $auth = new CF_Authentication($adapter_options['username'], $adapter_options['api_key'], null, 'UK' == $adapter_options['auth_host'] ? UK_AUTHURL : US_AUTHURL);
     $auth->authenticate();
     $conn = new CF_Connection($auth);
     try {
         $container = $conn->get_container($adapter_options['container']);
     } catch (NoSuchContainerException $e) {
         // Container doesn't already exist so create it
         $container = $conn->create_container($adapter_options['container']);
         $container->make_public();
     }
     return $container;
 }
Beispiel #13
0
/**
 * Get the Swift thumbnail container for this wiki.
 *
 * @param $site string
 * @param $lang string
 * @return CF_Container|null
 */
function wmfGetSwiftThumbContainer( $site, $lang ) {
	global $wmfSwiftConfig; // PrivateSettings.php

	$auth = new CF_Authentication(
		$wmfSwiftConfig['user'],
		$wmfSwiftConfig['key'],
		NULL,
		$wmfSwiftConfig['authUrl']
	);
	$auth->authenticate();

	$conn = new CF_Connection( $auth );

	$name = "{$site}-{$lang}-media-thumb"; // swift container name
	try {
		$container = $conn->get_container( $name );
	} catch ( NoSuchContainerException $e ) { // container not created yet
		$container = null;
		wfDebugLog( 'swiftThumb', "Could not access `{$name}`; container does not exist." );
	}

	return $container;
}
Beispiel #14
0
include_once 'lib/cloudfiles.php';
$mossoUsername = "******";
$mossoAPIKey = "----YOUR-MOSSO-API-KEY----";
$prefixToAddToContainers = '';
// Used only if you want to prepend anything to your new containers
@(include_once 'S3toMosso__private__.php');
// NEFSYS private accounts access. Remove if not NEFSYS
// Other settings
$directoryType = 'application/directory';
// Connect to S3
$objS3 = new S3($awsAccessID, $awsSecretKey);
// Connect to Mosso
$objMossoAuth = new CF_Authentication($mossoUsername, $mossoAPIKey);
$objMossoAuth->authenticate();
// Let's get a connection to CloudFiles
$objMosso = new CF_Connection($objMossoAuth);
echo "Listing buckets from your Amazon S3\n";
$awsBucketList = $objS3->listBuckets();
echo str_replace('Array', 'Amazon S3 Buckets', print_r($awsBucketList, true)) . "\n";
foreach ($awsBucketList as $awsBucketName) {
    if (in_array($awsBucketName, $awsExcludeBuckets)) {
        echo "---> Bucket {$awsBucketName} will be excluded\n";
        continue;
    }
    $mossoContainerName = $prefixToAddToContainers . $awsBucketName;
    // TODO: check if Bucket is CDN enabled
    // Get objects
    echo "Listing objects in Bucket {$awsBucketName} \n";
    $awsObjectList = $objS3->getBucket($awsBucketName);
    // Create this bucket as a Container on MOSSO
    echo "Creating Container {$mossoContainerName} in Cloud Files\n";
Beispiel #15
0
 function process_rackspace_copy($rs_backup, $rs_username, $rs_api_key, $rs_container, $rs_server)
 {
     pb_backupbuddy::set_greedy_script_limits();
     if (!class_exists('backupbuddy_core')) {
         require_once pb_backupbuddy::plugin_path() . '/classes/core.php';
     }
     require_once pb_backupbuddy::plugin_path() . '/destinations/rackspace/lib/rackspace/cloudfiles.php';
     $auth = new CF_Authentication($rs_username, $rs_api_key, NULL, $rs_server);
     $auth->authenticate();
     $conn = new CF_Connection($auth);
     // Set container
     $container = $conn->get_container($rs_container);
     // Get file from Rackspace
     $rsfile = $container->get_object($rs_backup);
     $destination_file = backupbuddy_core::getBackupDirectory() . $rs_backup;
     if (file_exists($destination_file)) {
         $destination_file = str_replace('backup-', 'backup_copy_' . pb_backupbuddy::random_string(5) . '-', $destination_file);
     }
     $fso = fopen(backupbuddy_core::getBackupDirectory() . $rs_backup, 'w');
     $rsfile->stream($fso);
     fclose($fso);
 }
Beispiel #16
0
$rs_api_key = $destination['api_key'];
$rs_container = $destination['container'];
$rs_server = $destination['server'];
/*
if ( isset( $destination['server'] ) ) {
	$rs_server = $destination['server'];
} else {
	$rs_server = 'https://auth.api.rackspacecloud.com';
}
$rs_path = ''; //$destination['path'];
*/
require_once pb_backupbuddy::plugin_path() . '/destinations/rackspace/lib/rackspace/cloudfiles.php';
$auth = new CF_Authentication($rs_username, $rs_api_key, NULL, $rs_server);
$auth->authenticate();
try {
    $conn = new CF_Connection($auth);
} catch (Exception $e) {
    echo 'Error #847834: Exception caught accessing Rackspace. If this persists try deleting (by selecting the configure destination button) & re-creating this destination. Details: `' . $e->getMessage() . '`.';
    die;
}
// Set container
$container = @$conn->get_container($rs_container);
// Delete Rackspace backups
if (!empty($_POST['delete_file'])) {
    pb_backupbuddy::verify_nonce();
    $delete_count = 0;
    if (!empty($_POST['files']) && is_array($_POST['files'])) {
        // loop through and delete Rackspace files
        foreach ($_POST['files'] as $rsfile) {
            $delete_count++;
            // Delete Rackspace file
<?php

ini_set("memory_limit", "512M");
require "php-cloudfiles-1.3.0/cloudfiles.php";
$backupsToKeep = 5;
// # of backup files to keep
$username = '******';
$apiKey = 'APIKEY';
$containerToUse = 'CLOUDCONTAINERNAME';
$baseDir = 'YOURSITEPATH/backup/';
$auth = new CF_Authentication($username, $apiKey);
$auth->authenticate();
$conn = new CF_Connection($auth);
$container = $conn->get_container($containerToUse);
function cleanup($prefix)
{
    global $container, $backupsToKeep;
    $list = $container->list_objects(0, NULL, $prefix);
    sort($list);
    $del_list = array_slice($list, 0, -($backupsToKeep - 1));
    foreach ($del_list as $file) {
        $container->delete_object($file);
        echo $file . ' deleted - ';
    }
}
function copytocloud($file, $objName)
{
    global $container, $baseDir;
    $object = $container->create_object($objName);
    $result = $object->load_from_filename($baseDir . $file);
    echo $object . ' copied - ';
Beispiel #18
0
 function afterDelete(&$model)
 {
     if ($this->_fileToRemove) {
         $conf = Configure::read('Trois.media');
         switch ($conf['fileEngine']) {
             case 'local':
                 $file = new File(WWW_ROOT . $this->_fileToRemove);
                 return $file->delete();
                 break;
             case 'cloudFiles':
                 App::import('Vendor', 'Trois.Cloudfiles', array('file' => 'php-cloudfiles' . DS . 'cloudfiles.php'));
                 $auth = new CF_Authentication($conf['user'], $conf['secret']);
                 $auth->authenticate();
                 $conn = new CF_Connection($auth);
                 $container = $conn->get_container($conf['base']);
                 return $container->delete_object($this->_fileToRemove);
                 break;
         }
     }
     return true;
 }
         $storageClient = new Microsoft_WindowsAzure_Storage_Blob($_POST['msazureHost'], $_POST['msazureAccName'], $_POST['msazureKey']);
         $result = $storageClient->createContainer($_POST['newmsazureContainer']);
         $jobvalues['msazureContainer'] = $result->Name;
     } catch (Exception $e) {
         $backwpup_message .= __($e->getMessage(), 'backwpup') . '<br />';
     }
 }
 if (!empty($_POST['rscUsername']) and !empty($_POST['rscAPIKey']) and !empty($_POST['newrscContainer'])) {
     //create new Rackspase Container if needed
     if (!class_exists('CF_Authentication')) {
         require_once dirname(__FILE__) . '/../libs/rackspace/cloudfiles.php';
     }
     try {
         $auth = new CF_Authentication($_POST['rscUsername'], $_POST['rscAPIKey']);
         if ($auth->authenticate()) {
             $conn = new CF_Connection($auth);
             $public_container = $conn->create_container($_POST['newrscContainer']);
             $public_container->make_private();
         }
     } catch (Exception $e) {
         $backwpup_message .= __($e->getMessage(), 'backwpup') . '<br />';
     }
 }
 if (isset($_POST['dropboxauthdel']) and !empty($_POST['dropboxauthdel'])) {
     $jobvalues['dropetoken'] = '';
     $jobvalues['dropesecret'] = '';
     $backwpup_message .= __('Dropbox authentication deleted!', 'backwpup') . '<br />';
 }
 if (!empty($_POST['sugaremail']) && !empty($_POST['sugarpass']) && $_POST['authbutton'] == __('Sugarsync authenticate!', 'backwpup')) {
     if (!class_exists('SugarSync')) {
         include_once realpath(dirname(__FILE__) . '/../libs/sugarsync.php');
Beispiel #20
0
 function test_rackspace($rs_username, $rs_api_key, $rs_container)
 {
     if (empty($rs_username) || empty($rs_api_key) || empty($rs_container)) {
         return 'Missing one or more required fields.';
     }
     require_once $this->_pluginPath . '/lib/rackspace/cloudfiles.php';
     $auth = new CF_Authentication($rs_username, $rs_api_key);
     if (!$auth->authenticate()) {
         return 'Unable to authenticate. Verify your username/api key.';
     }
     $conn = new CF_Connection($auth);
     // Set container
     if (false === ($container = @$conn->get_container($rs_container))) {
         return 'Invalid container. You must create it first.';
     }
     // Create test file
     $testbackup = @$container->create_object('backupbuddytest.txt');
     if (!$testbackup->load_from_filename($this->_pluginPath . '/readme.txt')) {
         return 'BackupBuddy was not able to write the test file.';
     }
     // Delete test file from Rackspace
     if (!$container->delete_object('backupbuddytest.txt')) {
         return 'Unable to delete file from container.';
     }
     return true;
     // Success
 }
Beispiel #21
0
$container_name = empty($_GET['container']) ? $container_name : $_GET['container'];
if (empty($container_name)) {
    $log->LogError('Container name MUST be set.');
    die('Container name MUST be set.');
}
$log->LogInfo('Received ' . $_FILES['filename']['name']);
include 'php-cloudfiles/cloudfiles.php';
// Extract user and api key from the http auth
$username = $_SERVER['PHP_AUTH_USER'];
$api_key = $_SERVER['PHP_AUTH_PW'];
// If there's a ?name= query variable, use that as the file name
$filename = empty($_GET['name']) ? $_FILES['filename']['name'] : $_GET['name'];
// Authenticate with CloudFiles and create our file and container objects
$auth = new CF_Authentication($username, $api_key);
$auth->authenticate();
$conn = new CF_Connection($auth);
$container = $conn->create_container($container_name);
$file = $container->create_object($filename);
// Set the content-type
if (class_exists('finfo')) {
    // Use the PECL finfo to determine mime type
    $finfo = new finfo(FILEINFO_MIME);
    // Rename the file so we get the right extension
    move_uploaded_file($_FILES['filename']['tmp_name'], "/tmp/{$filename}");
    $file->content_type = $finfo->file("/tmp/{$filename}");
} else {
    // PECL extension not installed, so try and guess
    $file->content_type = guessmime($filename);
}
$size = (double) sprintf("%u", filesize($_FILES['filename']['tmp_name']));
$fp = fopen($_FILES['filename']['tmp_name'], "r");
         die($e->getMessage());
     }
     break;
 case 'downloadrsc':
     //Download RSC Backup
     check_admin_referer('download-backup');
     if (!class_exists('CF_Authentication')) {
         require_once realpath(plugin_dir_path(__FILE__) . '/../libs/rackspace/cloudfiles.php');
     }
     $jobs = get_option('backwpup_jobs');
     $jobid = $_GET['jobid'];
     try {
         $auth = new CF_Authentication($jobs[$jobid]['rscUsername'], $jobs[$jobid]['rscAPIKey']);
         $auth->ssl_use_cabundle();
         if ($auth->authenticate()) {
             $conn = new CF_Connection($auth);
             $conn->ssl_use_cabundle();
             $backwpupcontainer = $conn->get_container($jobs[$jobid]['rscContainer']);
             $backupfile = $backwpupcontainer->get_object($_GET['file']);
             header("Pragma: public");
             header("Expires: 0");
             header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
             header("Content-Type: " . $backupfile->content_type);
             header("Content-Type: application/force-download");
             header("Content-Type: application/octet-stream");
             header("Content-Type: application/download");
             header("Content-Disposition: attachment; filename=" . basename($_GET['file']) . ";");
             header("Content-Transfer-Encoding: binary");
             header("Content-Length: " . $backupfile->content_length);
             $output = fopen("php://output", "w");
             $backupfile->stream($output);
#
out(sprintf('Initializing new CF_Authentication as "%s" / "%s"...', $user, $api_key), FALSE);
$auth = new CF_Authentication($user, $api_key);
out('Done.');
out('Authenticating with Rackspace Cloud Files...', FALSE);
$auth->authenticate();
out('Done.');
# Establish a connection to the storage system
#
# NOTE: Some versions of cURL include an outdated certificate authority (CA)
#       file.  This API ships with a newer version obtained directly from
#       cURL's web site (http://curl.haxx.se).  To use the newer CA bundle,
#       call the CF_Connection instance's 'ssl_use_cabundle()' method.
#
out('Establishing a new connection to storage system...', FALSE);
$conn = new CF_Connection($auth);
out('Done.');
out(sprintf('Getting existing remote Container "%s"...', $container_name), FALSE);
try {
    $container = $conn->get_container($container_name);
} catch (Exception $e) {
    out('Fail! Container does not exist!');
    //  out('Attempting to automatically create new remote Container...', FALSE);
    //  $container = $conn->create_container($container_name);
}
out('Done.');
if (is_dir($path)) {
    $dirs = array($path);
    while (NULL !== ($dir = array_pop($dirs))) {
        if ($dh = opendir($dir)) {
            while (FALSE !== ($_file = readdir($dh))) {
Beispiel #24
0
 function test_rackspace($rs_username, $rs_api_key, $rs_container, $rs_server)
 {
     if (empty($rs_username) || empty($rs_api_key) || empty($rs_container)) {
         return __('Missing one or more required fields.', 'it-l10n-backupbuddy');
     }
     require_once pb_backupbuddy::plugin_path() . '/lib/rackspace/cloudfiles.php';
     $auth = new CF_Authentication($rs_username, $rs_api_key, NULL, $rs_server);
     if (!$auth->authenticate()) {
         return __('Unable to authenticate. Verify your username/api key.', 'it-l10n-backupbuddy');
     }
     $conn = new CF_Connection($auth);
     // Set container
     $container = @$conn->get_container($rs_container);
     // returns object on success, string error message on failure.
     if (!is_object($container)) {
         return __('There was a problem selecting the container:', 'it-l10n-backupbuddy') . ' ' . $container;
     }
     // Create test file
     $testbackup = @$container->create_object('backupbuddytest.txt');
     if (!$testbackup->load_from_filename(pb_backupbuddy::plugin_path() . '/readme.txt')) {
         return __('BackupBuddy was not able to write the test file.', 'it-l10n-backupbuddy');
     }
     // Delete test file from Rackspace
     if (!$container->delete_object('backupbuddytest.txt')) {
         return __('Unable to delete file from container.', 'it-l10n-backupbuddy');
     }
     return true;
     // Success
 }
Beispiel #25
0
	function process_rackspace_copy( $rs_backup, $rs_username, $rs_api_key, $rs_container, $rs_server ) {
		pb_backupbuddy::set_greedy_script_limits();
		
		require_once( pb_backupbuddy::plugin_path() . '/lib/rackspace/cloudfiles.php' );
		$auth = new CF_Authentication( $rs_username, $rs_api_key, NULL, $rs_server );
		$auth->authenticate();
		$conn = new CF_Connection( $auth );

		// Set container
		$container = $conn->get_container( $rs_container );
		
		// Get file from Rackspace
		$rsfile = $container->get_object( $rs_backup );
		
		$destination_file = ABSPATH . 'wp-content/uploads/backupbuddy_backups/' . $rs_backup;
		if ( file_exists( $destination_file ) ) {
			$destination_file = str_replace( 'backup-', 'backup_copy_' . pb_backupbuddy::random_string( 5 ) . '-', $destination_file );
		}
		
		$fso = fopen( ABSPATH . 'wp-content/uploads/backupbuddy_backups/' . $rs_backup, 'w' );
		$rsfile->stream($fso);
		fclose($fso);
	}
Beispiel #26
0
<?php

// Inclusione della libreria php-cloudfiles
require 'php-cloudfiles/cloudfiles.php';
// Rackspace key
$user = "******";
$key = "chiave segreta API";
// Autenticazione con il servizio API di Rackspace
$auth = new CF_Authentication($user, $key);
try {
    $auth->authenticate();
} catch (Exception $e) {
    die('Errore: ' . $e->getMessage());
}
$conn = new CF_Connection($auth);
// Creazione di un container di prova
$container = $conn->create_container('test');
// Nome del file da memorizzare
$filename = 'picture.jpg';
// Invio del file a Rackspace
$object = $container->create_object($filename);
$object->load_from_filename($filename);
 /**
  * Uploads the final videos (flv, iso) to the Rackspace CDN
  */
 private function uploadToCDN()
 {
     require_once '_common/includes/rackspace_cloud_php/cloudfiles.php';
     require_once '_common/config/rackspace_cloud.php';
     // vars
     $container_name = $this->tributeId;
     $root_path = "/home/www/sites/worldwidememorials.net/htdocs/";
     $final_video_path = $root_path . $this->tributePath . "video/" . $this->randomCode . $this->videoFilename . '.' . $this->outputFormat;
     $final_iso_path = $root_path . $this->imagesPath . $this->randomCode . $this->videoFilename . '.iso';
     $object_name = md5(time() . $this->tributeId);
     // authentication process
     $cf_auth = new CF_Authentication($cloud_settings['production']['username'], $cloud_settings['production']['api_key']);
     $cf_auth->authenticate();
     // creates the connection
     $cf_conn = new CF_Connection($cf_auth);
     // creates the container
     $cf_container = $cf_conn->create_container($container_name);
     // deletes the previous files
     $cf_container_objects = $cf_container->list_objects();
     foreach ($cf_container_objects as $object) {
         $cf_container->delete_object($object);
     }
     // creates and upload the flv video¡
     $cf_flv = $cf_container->create_object($object_name . '.flv');
     $cf_flv->content_type = "video/x-flv";
     $cf_flv->load_from_filename($final_video_path);
     // creates and upload the iso file
     $cf_iso = $cf_container->create_object($object_name . '.iso');
     $cf_iso->content_type = "application/x-iso-image";
     $cf_iso->load_from_filename($final_iso_path);
     // makes the container public
     $public_container = $cf_container->make_public();
     $this->vars['filename'] = $public_container . '/' . $object_name . '.' . $this->outputFormat;
     $this->nextStep(false);
 }
 function _serve_file($link_id, $storage, $container, $endpoint, $url, $filename, $type, $file_id, $inline = false)
 {
     //echo $link_id.", <br />".$storage.", <br />".$container.", <br />".$endpoint.", <br />".$url.", <br />".$filename.",  <br />".$type.", <br />".$file_id.", <br />".$inline;
     if ($this->EE->session->userdata('group_id') != 1) {
         $this->EE->db->query("INSERT INTO exp_protected_links_stats (link_id, file_id, member_id, ip, dl_date) VALUES ('{$link_id}', '{$file_id}', '" . $this->EE->session->userdata('member_id') . "', '" . $this->EE->input->ip_address . "', '" . $this->EE->localize->now . "')");
         $this->EE->db->query("UPDATE exp_protected_links_files SET dl_count=dl_count+1, dl_date='" . $this->EE->localize->now . "' WHERE file_id={$file_id}");
         $this->EE->db->query("UPDATE exp_protected_links_links SET dl_count=dl_count+1 WHERE link_id={$link_id}");
     }
     $filename = strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? preg_replace('/\\./', '%2e', $filename, substr_count($filename, '.') - 1) : $filename;
     switch ($storage) {
         case 'local':
             $url = urldecode($url);
             if (!file_exists($url)) {
                 return $this->EE->output->show_user_error('general', array($this->EE->lang->line('file_not_exist')));
             }
             header("Pragma: public");
             header("Expires: 0");
             header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
             header("Cache-Control: public", FALSE);
             header("Content-Description: File Transfer");
             header("Content-Type: " . $type);
             header("Accept-Ranges: bytes");
             if ($inline == true) {
                 header("Content-Disposition: inline; filename=\"" . $filename . "\";");
             } else {
                 header("Content-Disposition: attachment; filename=\"" . $filename . "\";");
             }
             header("Content-Transfer-Encoding: binary");
             header('Content-Length: ' . filesize($url));
             @ob_clean();
             @flush();
             @readfile($url);
             break;
         case 'url':
             $use_curl = true;
             if (!function_exists('curl_init')) {
                 $use_curl = false;
                 //return $this->EE->output->show_user_error('general', array($this->EE->lang->line('curl_required')));
             } else {
                 $curl = curl_init();
                 curl_setopt($curl, CURLOPT_URL, str_replace('&#47;', '/', $url));
                 curl_setopt($curl, CURLOPT_HEADER, true);
                 curl_setopt($curl, CURLOPT_NOBODY, true);
                 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                 if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
                     curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
                 }
                 curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                 curl_setopt($curl, CURLOPT_SSLVERSION, 3);
                 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
                 curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
                 $out = curl_exec($curl);
                 $error = curl_error($curl);
                 if ($error != '') {
                     return $this->EE->output->show_user_error('general', array($this->EE->lang->line('curl_error') . $error));
                 }
                 $size = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
                 curl_close($curl);
                 $memory = memory_get_usage(true);
                 if ($size > $memory * 3 / 4) {
                     $use_curl = false;
                 }
             }
             header("Pragma: public");
             header("Expires: 0");
             header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
             header("Cache-Control: public", FALSE);
             header("Content-Description: File Transfer");
             header("Content-Type: " . $type);
             header("Accept-Ranges: bytes");
             if ($inline == true) {
                 header("Content-Disposition: inline; filename=\"" . $filename . "\";");
             } else {
                 header("Content-Disposition: attachment; filename=\"" . $filename . "\";");
             }
             header("Content-Transfer-Encoding: binary");
             if ($use_curl == true) {
                 $curl = curl_init();
                 curl_setopt($curl, CURLOPT_URL, str_replace('&#47;', '/', $url));
                 curl_setopt($curl, CURLOPT_HEADER, false);
                 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                 if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
                     curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
                 }
                 curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                 curl_setopt($curl, CURLOPT_SSLVERSION, 3);
                 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
                 curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
                 $out = curl_exec($curl);
                 curl_close($curl);
                 echo $out;
             } else {
                 $fp = fopen(str_replace('&#47;', '/', $url), "rb");
                 while (!feof($fp)) {
                     echo fread($fp, 4096);
                     flush();
                 }
                 fclose($fp);
             }
             break;
         case 's3':
         case 'S3':
             require_once PATH_THIRD . "protected_links/storage_api/amazon/S3.php";
             header("Pragma: public");
             header("Expires: 0");
             header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
             header("Cache-Control: public", FALSE);
             header("Content-Description: File Transfer");
             header("Content-Type: " . $type);
             header("Accept-Ranges: bytes");
             if ($inline == true) {
                 header("Content-Disposition: inline; filename=\"" . $filename . "\";");
             } else {
                 header("Content-Disposition: attachment; filename=\"" . $filename . "\";");
             }
             header("Content-Transfer-Encoding: binary");
             $s3 = new S3($this->settings['s3_key_id'], $this->settings['s3_key_value']);
             if ($endpoint != '') {
                 $s3->setEndpoint($endpoint);
             }
             $fp = fopen("php://output", "wb");
             $s3->getObject("{$container}", $url, $fp);
             fclose($fp);
             break;
         case 'rackspace':
             require_once PATH_THIRD . "protected_links/storage_api/rackspace/cloudfiles.php";
             header("Pragma: public");
             header("Expires: 0");
             header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
             header("Cache-Control: public", FALSE);
             header("Content-Description: File Transfer");
             header("Content-Type: " . $type);
             header("Accept-Ranges: bytes");
             if ($inline == true) {
                 header("Content-Disposition: inline; filename=\"" . $filename . "\";");
             } else {
                 header("Content-Disposition: attachment; filename=\"" . $filename . "\";");
             }
             header("Content-Transfer-Encoding: binary");
             $auth = new CF_Authentication($this->settings['rackspace_api_login'], $this->settings['rackspace_api_password']);
             $auth->authenticate();
             $conn = new CF_Connection($auth);
             $container = $conn->get_container("{$container}");
             $fp = fopen("php://output", "wb");
             $url->stream($fp);
             fclose($fp);
             break;
     }
     exit;
 }
Beispiel #29
0
function backwpup_get_backup_files($jobid, $dest)
{
    global $backwpup_message;
    if (empty($jobid) or !in_array(strtoupper($dest), explode(',', strtoupper(BACKWPUP_DESTS))) and $dest != 'FOLDER') {
        return false;
    }
    $jobs = get_option('backwpup_jobs');
    //Load jobs
    $jobvalue = $jobs[$jobid];
    $filecounter = 0;
    $files = array();
    //Get files/filinfo in backup folder
    if ($dest == 'FOLDER' and !empty($jobvalue['backupdir']) and is_dir($jobvalue['backupdir'])) {
        if ($dir = opendir($jobvalue['backupdir'])) {
            while (($file = readdir($dir)) !== false) {
                if (substr($file, 0, 1) == '.') {
                    continue;
                }
                if (is_file($jobvalue['backupdir'] . $file)) {
                    $files[$filecounter]['JOBID'] = $jobid;
                    $files[$filecounter]['DEST'] = $dest;
                    $files[$filecounter]['folder'] = $jobvalue['backupdir'];
                    $files[$filecounter]['file'] = $jobvalue['backupdir'] . $file;
                    $files[$filecounter]['filename'] = $file;
                    $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=download&file=' . $jobvalue['backupdir'] . $file;
                    $files[$filecounter]['filesize'] = filesize($jobvalue['backupdir'] . $file);
                    $files[$filecounter]['time'] = filemtime($jobvalue['backupdir'] . $file);
                    $filecounter++;
                }
            }
            closedir($dir);
        }
    }
    //Get files/filinfo from Dropbox
    if ($dest == 'DROPBOX' and !empty($jobvalue['dropetoken']) and !empty($jobvalue['dropesecret'])) {
        require_once realpath(dirname(__FILE__) . '/../libs/dropbox.php');
        try {
            $dropbox = new backwpup_Dropbox('dropbox');
            $dropbox->setOAuthTokens($jobvalue['dropetoken'], $jobvalue['dropesecret']);
            $contents = $dropbox->metadata($jobvalue['dropedir']);
            if (is_array($contents)) {
                foreach ($contents['contents'] as $object) {
                    if ($object['is_dir'] != true) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "https://api-content.dropbox.com/1/files/" . $jobvalue['droperoot'] . "/" . dirname($object['path']) . "/";
                        $files[$filecounter]['file'] = $object['path'];
                        $files[$filecounter]['filename'] = basename($object['path']);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloaddropbox&file=' . $object['path'] . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = $object['bytes'];
                        $files[$filecounter]['time'] = strtotime($object['modified']);
                        $filecounter++;
                    }
                }
            }
        } catch (Exception $e) {
            $backwpup_message .= 'DROPBOX: ' . $e->getMessage() . '<br />';
        }
    }
    //Get files/filinfo from Sugarsync
    if ($dest == 'SUGARSYNC' and !empty($jobvalue['sugarrefreshtoken'])) {
        if (!class_exists('SugarSync')) {
            require_once dirname(__FILE__) . '/../libs/sugarsync.php';
        }
        if (class_exists('SugarSync')) {
            try {
                $sugarsync = new SugarSync($jobvalue['sugarrefreshtoken']);
                $dirid = $sugarsync->chdir($jobvalue['sugardir'], $jobvalue['sugarroot']);
                $user = $sugarsync->user();
                $dir = $sugarsync->showdir($dirid);
                $getfiles = $sugarsync->getcontents('file');
                if (is_object($getfiles)) {
                    foreach ($getfiles->file as $getfile) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = 'https://' . $user->nickname . '.sugarsync.com/' . $dir;
                        $files[$filecounter]['file'] = (string) $getfile->ref;
                        $files[$filecounter]['filename'] = utf8_decode((string) $getfile->displayName);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloadsugarsync&file=' . (string) $getfile->ref . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = (int) $getfile->size;
                        $files[$filecounter]['time'] = strtotime((string) $getfile->lastModified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= 'SUGARSYNC: ' . $e->getMessage() . '<br />';
            }
        }
    }
    //Get files/filinfo from S3
    if ($dest == 'S3' and !empty($jobvalue['awsAccessKey']) and !empty($jobvalue['awsSecretKey']) and !empty($jobvalue['awsBucket'])) {
        if (!class_exists('AmazonS3')) {
            require_once dirname(__FILE__) . '/../libs/aws/sdk.class.php';
        }
        if (class_exists('AmazonS3')) {
            try {
                $s3 = new AmazonS3(array('key' => $jobvalue['awsAccessKey'], 'secret' => $jobvalue['awsSecretKey'], 'certificate_authority' => true));
                if (($contents = $s3->list_objects($jobvalue['awsBucket'], array('prefix' => $jobvalue['awsdir']))) !== false) {
                    foreach ($contents->body->Contents as $object) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "https://" . $jobvalue['awsBucket'] . ".s3.amazonaws.com/" . dirname((string) $object->Key) . '/';
                        $files[$filecounter]['file'] = (string) $object->Key;
                        $files[$filecounter]['filename'] = basename($object->Key);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloads3&file=' . $object->Key . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = (string) $object->Size;
                        $files[$filecounter]['time'] = strtotime($object->LastModified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= 'Amazon S3: ' . $e->getMessage() . '<br />';
            }
        }
    }
    //Get files/filinfo from Google Storage
    if ($dest == 'GSTORAGE' and !empty($jobvalue['GStorageAccessKey']) and !empty($jobvalue['GStorageSecret']) and !empty($jobvalue['GStorageBucket'])) {
        if (!class_exists('AmazonS3')) {
            require_once dirname(__FILE__) . '/../libs/aws/sdk.class.php';
        }
        if (class_exists('AmazonS3')) {
            try {
                $gstorage = new AmazonS3(array('key' => $jobvalue['GStorageAccessKey'], 'secret' => $jobvalue['GStorageSecret'], 'certificate_authority' => true));
                $gstorage->set_hostname('storage.googleapis.com');
                $gstorage->allow_hostname_override(false);
                if (($contents = $gstorage->list_objects($jobvalue['GStorageBucket'], array('prefix' => $jobvalue['GStoragedir']))) !== false) {
                    foreach ($contents->body->Contents as $object) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "https://storage.cloud.google.com/" . $jobvalue['GStorageBucket'] . "/" . dirname((string) $object->Key) . '/';
                        $files[$filecounter]['file'] = (string) $object->Key;
                        $files[$filecounter]['filename'] = basename($object->Key);
                        $files[$filecounter]['downloadurl'] = "https://storage.cloud.google.com/" . $jobvalue['GStorageBucket'] . "/" . (string) $object->Key;
                        $files[$filecounter]['filesize'] = (string) $object->Size;
                        $files[$filecounter]['time'] = strtotime($object->LastModified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= sprintf(__('GStorage API: %s', 'backwpup'), $e->getMessage()) . '<br />';
            }
        }
    }
    //Get files/filinfo from Microsoft Azure
    if ($dest == 'MSAZURE' and !empty($jobvalue['msazureHost']) and !empty($jobvalue['msazureAccName']) and !empty($jobvalue['msazureKey']) and !empty($jobvalue['msazureContainer'])) {
        if (!class_exists('Microsoft_WindowsAzure_Storage_Blob')) {
            require_once dirname(__FILE__) . '/../libs/Microsoft/WindowsAzure/Storage/Blob.php';
        }
        if (class_exists('Microsoft_WindowsAzure_Storage_Blob')) {
            try {
                $storageClient = new Microsoft_WindowsAzure_Storage_Blob($jobvalue['msazureHost'], $jobvalue['msazureAccName'], $jobvalue['msazureKey']);
                $blobs = $storageClient->listBlobs($jobvalue['msazureContainer'], $jobvalue['msazuredir']);
                if (is_array($blobs)) {
                    foreach ($blobs as $blob) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "https://" . $jobvalue['msazureAccName'] . '.' . $jobvalue['msazureHost'] . "/" . $jobvalue['msazureContainer'] . "/" . dirname($blob->Name) . "/";
                        $files[$filecounter]['file'] = $blob->Name;
                        $files[$filecounter]['filename'] = basename($blob->Name);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloadmsazure&file=' . $blob->Name . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = $blob->size;
                        $files[$filecounter]['time'] = strtotime($blob->lastmodified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= 'MSAZURE: ' . $e->getMessage() . '<br />';
            }
        }
    }
    //Get files/filinfo from RSC
    if ($dest == 'RSC' and !empty($jobvalue['rscUsername']) and !empty($jobvalue['rscAPIKey']) and !empty($jobvalue['rscContainer'])) {
        if (!class_exists('CF_Authentication')) {
            require_once dirname(__FILE__) . '/../libs/rackspace/cloudfiles.php';
        }
        if (class_exists('CF_Authentication')) {
            try {
                $auth = new CF_Authentication($jobvalue['rscUsername'], $jobvalue['rscAPIKey']);
                $auth->ssl_use_cabundle();
                if ($auth->authenticate()) {
                    $conn = new CF_Connection($auth);
                    $conn->ssl_use_cabundle();
                    $backwpupcontainer = $conn->get_container($jobvalue['rscContainer']);
                    $contents = $backwpupcontainer->get_objects(0, NULL, NULL, $jobvalue['rscdir']);
                    foreach ($contents as $object) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "RSC://" . $jobvalue['rscContainer'] . "/" . dirname($object->name) . "/";
                        $files[$filecounter]['file'] = $object->name;
                        $files[$filecounter]['filename'] = basename($object->name);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloadrsc&file=' . $object->name . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = $object->content_length;
                        $files[$filecounter]['time'] = strtotime($object->last_modified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= 'RSC: ' . $e->getMessage() . '<br />';
            }
        }
    }
    //Get files/filinfo from FTP
    if ($dest == 'FTP' and !empty($jobvalue['ftphost']) and function_exists('ftp_connect') and !empty($jobvalue['ftpuser']) and !empty($jobvalue['ftppass'])) {
        if (function_exists('ftp_ssl_connect') and $jobvalue['ftpssl']) {
            //make SSL FTP connection
            $ftp_conn_id = ftp_ssl_connect($jobvalue['ftphost'], $jobvalue['ftphostport'], 10);
        } elseif (!$jobvalue['ftpssl']) {
            //make normal FTP conection if SSL not work
            $ftp_conn_id = ftp_connect($jobvalue['ftphost'], $jobvalue['ftphostport'], 10);
        }
        $loginok = false;
        if ($ftp_conn_id) {
            //FTP Login
            if (@ftp_login($ftp_conn_id, $jobvalue['ftpuser'], backwpup_base64($jobvalue['ftppass']))) {
                $loginok = true;
            } else {
                //if PHP ftp login don't work use raw login
                ftp_raw($ftp_conn_id, 'USER ' . $jobvalue['ftpuser']);
                $return = ftp_raw($ftp_conn_id, 'PASS ' . backwpup_base64($jobvalue['ftppass']));
                if (substr(trim($return[0]), 0, 3) <= 400) {
                    $loginok = true;
                }
            }
        }
        if ($loginok) {
            ftp_chdir($ftp_conn_id, $jobvalue['ftpdir']);
            $currentftpdir = rtrim(ftp_pwd($ftp_conn_id), '/') . '/';
            ftp_pasv($ftp_conn_id, $jobvalue['ftppasv']);
            if ($ftpfilelist = ftp_nlist($ftp_conn_id, $currentftpdir)) {
                foreach ($ftpfilelist as $ftpfiles) {
                    if (substr(basename($ftpfiles), 0, 1) == '.') {
                        continue;
                    }
                    $files[$filecounter]['JOBID'] = $jobid;
                    $files[$filecounter]['DEST'] = $dest;
                    $files[$filecounter]['folder'] = "ftp://" . $jobvalue['ftphost'] . ':' . $jobvalue['ftphostport'] . dirname($ftpfiles) . "/";
                    $files[$filecounter]['file'] = $ftpfiles;
                    $files[$filecounter]['filename'] = basename($ftpfiles);
                    $files[$filecounter]['downloadurl'] = "ftp://" . rawurlencode($jobvalue['ftpuser']) . ":" . rawurlencode(backwpup_base64($jobvalue['ftppass'])) . "@" . $jobvalue['ftphost'] . ':' . $jobvalue['ftphostport'] . $ftpfiles;
                    $files[$filecounter]['filesize'] = ftp_size($ftp_conn_id, $ftpfiles);
                    $files[$filecounter]['time'] = ftp_mdtm($ftp_conn_id, $ftpfiles);
                    $filecounter++;
                }
            }
        } else {
            $backwpup_message .= 'FTP: ' . __('Login failure!', 'backwpup') . '<br />';
        }
        $donefolders[] = $jobvalue['ftphost'] . '|' . $jobvalue['ftpuser'] . '|' . $jobvalue['ftpdir'];
    }
    return $files;
}
 public function transer_dir($image_id)
 {
     $this->EE->load->helper('file');
     // Grab image info
     $query = $this->EE->db->select('field_id, entry_id, filename, extension')->from('exp_channel_images')->where('image_id', $image_id)->limit(1)->get();
     $field_id = $query->row('field_id');
     // Grab settings
     $settings = $this->EE->image_helper->grabFieldSettings($field_id);
     $filename = $query->row('filename');
     $extension = '.' . substr(strrchr($filename, '.'), 1);
     $entry_id = $query->row('entry_id');
     // -----------------------------------------
     // Load Location
     // -----------------------------------------
     $location_type = $settings['upload_location'];
     $location_class = 'CI_Location_' . $location_type;
     // Load Settings
     if (isset($settings['locations'][$location_type]) == FALSE) {
         $o['body'] = $this->EE->lang->line('ci:location_settings_failure');
         exit($this->EE->image_helper->generate_json($o));
     }
     $location_settings = $settings['locations'][$location_type];
     // Load Main Class
     if (class_exists('Image_Location') == FALSE) {
         require PATH_THIRD . 'channel_images/locations/image_location.php';
     }
     // Try to load Location Class
     if (class_exists($location_class) == FALSE) {
         $location_file = PATH_THIRD . 'channel_images/locations/' . $location_type . '/' . $location_type . '.php';
         if (file_exists($location_file) == FALSE) {
             $o['body'] = $this->EE->lang->line('ci:location_load_failure');
             exit($this->EE->image_helper->generate_json($o));
         }
         require $location_file;
     }
     // Init
     $LOC = new $location_class($location_settings);
     // Temp Dir
     @mkdir($this->EE->channel_images->cache_path . 'channel_images/', 0777);
     @mkdir($this->EE->channel_images->cache_path . 'channel_images/transfer/', 0777);
     @mkdir($this->EE->channel_images->cache_path . 'channel_images/transfer/' . $image_id . '/', 0777);
     $temp_dir = $this->EE->channel_images->cache_path . 'channel_images/transfer/' . $image_id . '/';
     // -----------------------------------------
     // Copy Image to temp location
     // -----------------------------------------
     $LOC->download_file($entry_id, $filename, $temp_dir);
     //if ($response !== TRUE) exit($response);
     foreach ($settings['action_groups'] as $group) {
         $size_name = $group['group_name'];
         $size_filename = str_replace($extension, "__{$size_name}{$extension}", $filename);
         $LOC->download_file($entry_id, $size_filename, $temp_dir);
     }
     // -----------------------------------------
     // Init Amazon
     // -----------------------------------------
     if ($_POST['transfer']['to'] == 's3') {
         if (class_exists('CFRuntime') == FALSE) {
             // Include the SDK
             require_once PATH_THIRD . 'channel_images/locations/s3/sdk/sdk.class.php';
         }
         // Just to be sure
         if (class_exists('AmazonS3') == FALSE) {
             include PATH_THIRD . 'channel_images/locations/s3/sdk/services/s3.class.php';
         }
         // Instantiate the AmazonS3 class
         $S3 = new AmazonS3(array('key' => trim($_POST['s3']['key']), 'secret' => trim($_POST['s3']['secret_key'])));
         $S3->ssl_verification = FALSE;
         // Init Configs
         $temp = $this->EE->config->item('ci_s3_storage');
         $s3_storage = constant('AmazonS3::' . $temp[$_POST['s3']['storage']]);
         $temp = $this->EE->config->item('ci_s3_acl');
         $s3_acl = constant('AmazonS3::' . $temp[$_POST['s3']['acl']]);
         $s3_directory = trim($_POST['s3']['directory']);
         $s3_bucket = $_POST['s3']['bucket'];
         $s3_subdir = '';
         if ($s3_directory) {
             $s3_subdir = $s3_directory . '/';
         }
         $s3_headers = $this->EE->config->item('ci_s3_headers');
         // Test it
         $resp = $S3->get_bucket_headers($s3_bucket);
         if (!$resp->isOK()) {
             if (isset($resp->body->Message)) {
                 exit('ERROR_S3: ' . $resp->body->Message);
             } else {
                 exit('ERROR_S3: Bucket error');
             }
         }
     } else {
         // Include the SDK
         if (class_exists('CF_Authentication') == FALSE) {
             require_once PATH_THIRD . 'channel_images/locations/cloudfiles/sdk/cloudfiles.php';
         }
         // Which Region?
         if ($_POST['cloudfiles']['region'] == 'uk') {
             $_POST['cloudfiles']['region'] = constant('UK_AUTHURL');
         } else {
             $_POST['cloudfiles']['region'] = constant('US_AUTHURL');
         }
         // Instantiate the Cloudfiles class
         $CF_AUTH = new CF_Authentication($_POST['cloudfiles']['username'], $_POST['cloudfiles']['api'], NULL, $_POST['cloudfiles']['region']);
         try {
             $CF_AUTH->ssl_use_cabundle();
             $CF_AUTH->authenticate();
         } catch (AuthenticationException $e) {
             exit('ERROR_CLOUDFILES:' . $e->getMessage());
         }
         $CF_CONN = new CF_Connection($CF_AUTH);
         $CF_CONN->ssl_use_cabundle();
         $CF_CONT = $CF_CONN->get_container($_POST['cloudfiles']['container']);
     }
     // -----------------------------------------
     // Loop over all dirs
     // -----------------------------------------
     $files = scandir($temp_dir);
     foreach ($files as $file) {
         $full_path = $temp_dir . $file;
         if (is_file($full_path) == false) {
             continue;
         }
         $extension = substr(strrchr($file, '.'), 1);
         // Mime type
         if ($extension == 'jpg') {
             $filemime = 'image/jpeg';
         } elseif ($extension == 'jpeg') {
             $filemime = 'image/jpeg';
         } elseif ($extension == 'png') {
             $filemime = 'image/png';
         } elseif ($extension == 'gif') {
             $filemime = 'image/gif';
         } else {
             continue;
         }
         if (isset($S3) == true) {
             $upload_arr = array();
             $upload_arr['fileUpload'] = $full_path;
             $upload_arr['contentType'] = $filemime;
             $upload_arr['acl'] = $s3_acl;
             $upload_arr['storage'] = $s3_storage;
             $upload_arr['headers'] = array();
             if ($s3_headers != FALSE && is_array($s3_headers) === TRUE) {
                 $upload_arr['headers'] = $s3_headers;
             }
             $response = $S3->create_object($s3_bucket, $s3_subdir . $entry_id . '/' . $file, $upload_arr);
             // Success?
             if (!$response->isOK()) {
                 exit((string) $response->body->Message);
             }
         } else {
             $OBJECT = $CF_CONT->create_object($entry_id . '/' . $file);
             $OBJECT->content_type = $filemime;
             try {
                 $OBJECT->load_from_filename($full_path);
             } catch (Exception $e) {
                 exit($e->getMessage());
             }
         }
         //@unlink($temp_dir.$file);
     }
     @delete_files($temp_dir, true);
     @rmdir($temp_dir);
     $o = array('success' => 'yes');
     exit($this->EE->image_helper->generate_json($o));
 }