public function execute(WPAdm_Command_Context $context)
 {
     require_once WPAdm_Core::getPluginDir() . '/modules/aws-autoloader.php';
     $credentials = new Aws\Common\Credentials\Credentials($context->get('AccessKeyId'), $context->get('SecretAccessKey'));
     $client = Aws\S3\S3Client::factory(array('credentials' => $credentials));
     $dir = $context->get('dir') ? $context->get('dir') . "/" : '';
     try {
         if (!empty($dir)) {
             $logs = $client->putObject(array('Bucket' => $context->get('bucket'), 'Key' => $dir, 'Body' => ''));
             WPAdm_Core::log('Create folder ' . $dir);
         }
         $filePath = preg_replace('#[/\\\\]+#', '/', $context->get('file'));
         $key = $dir ? $dir . '/' . basename($filePath) : basename($filePath);
         $key = ltrim(preg_replace('#[/\\\\]+#', '/', $key), '/');
         //if first will be '/', file not will be uploaded, but result will be ok
         $putRes = $client->putObject(array("Bucket" => $context->get('bucket'), 'Key' => $key, 'Body' => fopen($filePath, 'r+')));
         if ((int) $putRes == 1) {
             WPAdm_Core::log("File({$key}) Upload successfully to Amazon S3");
         }
     } catch (Exception $e) {
         $context->setError($e->getMessage());
         return false;
     } catch (S3Exception $e) {
         WPAdm_Core::log('error send file ' . $e->getMessage());
         $context->setError($e->getMessage());
         return false;
     }
     return true;
 }
Пример #2
0
 public static function uploadToAmazon($file, $key)
 {
     $client = Aws\S3\S3Client::factory(['region' => 'us-west-2', 'version' => '2006-03-01', 'http' => ['verify' => false]]);
     $bucket = getenv('S3_BUCKET') ?: die('No "S3_BUCKET" config var in found in env!');
     $result = $client->putObject(array('Bucket' => $bucket, 'Key' => 'posts/' . $key, 'SourceFile' => $file));
     return $result;
 }
Пример #3
0
 public function run()
 {
     include main::getPluginDir() . '/libs/classes/aws-autoloader.php';
     $ad = $this->params['access_details'];
     main::log(lang::get('Start copy files to Amazon S3', false));
     $files = $this->params['files'];
     $dir = isset($ad['dir']) ? $ad['dir'] : '/';
     $credentials = new Aws\Common\Credentials\Credentials($ad['AccessKeyId'], $ad['SecretAccessKey']);
     $client = Aws\S3\S3Client::factory(array('credentials' => $credentials));
     try {
         $n = count($files);
         for ($i = 0; $i < $n; $i++) {
             $filePath = preg_replace('#[/\\\\]+#', '/', BACKUP_DIR . '/' . $dir . '/' . $files[$i]);
             $key = $dir ? $dir . '/' . basename($filePath) : basename($filePath);
             $key = ltrim(preg_replace('#[/\\\\]+#', '/', $key), '/');
             //if first will be '/', file not will be uploaded, but result will be ok
             $putRes = $client->putObject(array("Bucket" => $ad['bucket'], 'Key' => $key, 'Body' => fopen($filePath, 'r+')));
             if (isset($putRes['RequestId']) && !empty($putRes['RequestId'])) {
                 main::log(str_replace('%s', basename($filePath), lang::get("File(%s) Upload successfully to Amazon S3", false)));
             }
         }
         main::log(lang::get('End copy files to Amazon S3', false));
     } catch (Exception $e) {
         main::log('Error send to Amazon s3: ' . $e->getMessage());
         $this->setError($e->getMessage());
         return false;
     } catch (S3Exception $e) {
         main::log('Error send to Amazon s3: ' . $e->getMessage());
         $this->setError($e->getMessage());
         return false;
     }
     return true;
 }
Пример #4
0
 /**
  * @throws \Aws\S3\Exception\BucketAlreadyOwnedByYouException
  * @throws \Aws\S3\Exception\OperationAbortedException
  */
 protected function _createBucket()
 {
     $options = array('Bucket' => $this->_bucket);
     $region = $this->_client->getRegion();
     if ($region != 'us-east-1') {
         $options['LocationConstraint'] = $region;
     }
     $this->_client->createBucket($options);
 }
 /**
  * Send the file to S3 for persistence.
  *
  * If we want to just store it locally to the server receiving the request,
  * simply use move_uploaded_file() to save the uploaded CSS and write
  * the report to the same location in a similar fashion.
  *
  * @param string $filePath
  * @param string $fileExtension
  * @return string
  * @throws S3BucketNotFoundException
  */
 private function persistFileToS3($filePath, $fileExtension)
 {
     $s3Client = Aws\S3\S3Client::factory();
     $s3Bucket = getenv('S3_BUCKET');
     if (!$s3Bucket) {
         throw new S3BucketNotFoundException('S3 persistent storage missing bucket in configuration.');
     }
     $fileName = $this->sessionUUID . '.' . $fileExtension;
     $uploadHandle = $s3Client->upload($s3Bucket, $fileName, fopen($filePath, 'rb'), 'public-read');
     return htmlspecialchars($uploadHandle->get('ObjectURL'));
 }
Пример #6
0
 private function getFilesToDownloadFromManifest($path)
 {
     $s3Client = new \Aws\S3\S3Client(['credentials' => ['key' => $this->s3key, 'secret' => $this->s3secret], 'region' => $this->s3region, 'version' => '2006-03-01']);
     $path = parse_url($path);
     try {
         $response = $s3Client->getObject(['Bucket' => $path['host'], 'Key' => ltrim($path['path'], '/')]);
     } catch (AwsException $e) {
         throw new Exception('Unable to download file from S3: ' . $e->getMessage());
     }
     $manifest = json_decode((string) $response['Body'], true);
     return array_map(function ($entry) use($s3Client) {
         $path = parse_url($entry['url']);
         try {
             // file validation
             $s3Client->headObject(['Bucket' => $path['host'], 'Key' => ltrim($path['path'], '/')]);
         } catch (S3Exception $e) {
             throw new Exception(sprintf('File "%s" download error: %s', $entry['url'], $e->getMessage()), Exception::MANDATORY_FILE_NOT_FOUND);
         }
         return $entry['url'];
     }, $manifest['entries']);
 }
 private function uploadToS3Bucket($filename, $fileData, &$message)
 {
     $client = Aws\S3\S3Client::factory(ConnectionManager::getDataSource('default')->config['aws_s3_config']['aws_config']);
     $bucket = ConnectionManager::getDataSource('default')->config['aws_s3_config']['aws_bucket'];
     $data = explode(',', $fileData);
     try {
         $result = $client->putObject(array('Bucket' => $bucket, 'Key' => $filename, 'Body' => base64_decode($data[0]), 'ContentType' => 'image/jpeg', 'ACL' => 'public-read'));
         return $result['ObjectURL'];
     } catch (Exception $e) {
         $message = $e->getMessage();
         return null;
     }
 }
Пример #8
0
 /**
  * @param Repository $repoObject
  * @param boolean $registerStream
  * @return \AccessS3\S3Client
  */
 protected static function getClientForRepository($repoObject, $registerStream = true)
 {
     require_once "aws.phar";
     if (!isset(self::$clients[$repoObject->getId()])) {
         // Get a client
         $options = array('key' => $repoObject->getOption("API_KEY"), 'secret' => $repoObject->getOption("SECRET_KEY"));
         $signatureVersion = $repoObject->getOption("SIGNATURE_VERSION");
         if (!empty($signatureVersion)) {
             $options['signature'] = $signatureVersion;
         }
         $baseURL = $repoObject->getOption("STORAGE_URL");
         if (!empty($baseURL)) {
             $options["base_url"] = $baseURL;
         }
         $region = $repoObject->getOption("REGION");
         if (!empty($region)) {
             $options["region"] = $region;
         }
         $proxy = $repoObject->getOption("PROXY");
         if (!empty($proxy)) {
             $options['request.options'] = array('proxy' => $proxy);
         }
         $apiVersion = $repoObject->getOption("API_VERSION");
         if ($apiVersion === "") {
             $apiVersion = "latest";
         }
         //SDK_VERSION IS A GLOBAL PARAM
         ConfService::getConfStorageImpl()->_loadPluginConfig("access.s3", $globalOptions);
         $sdkVersion = $globalOptions["SDK_VERSION"];
         //$repoObject->driverInstance->driverConf['SDK_VERSION'];
         if ($sdkVersion !== "v2" && $sdkVersion !== "v3") {
             $sdkVersion = "v2";
         }
         if ($sdkVersion === "v3") {
             require_once __DIR__ . DIRECTORY_SEPARATOR . "class.pydioS3Client.php";
             $s3Client = new \AccessS3\S3Client(["version" => $apiVersion, "region" => $region, "credentials" => $options]);
             $s3Client->registerStreamWrapper($repoObject->getId());
         } else {
             $s3Client = Aws\S3\S3Client::factory($options);
             if ($repoObject->getOption("VHOST_NOT_SUPPORTED")) {
                 // Use virtual hosted buckets when possible
                 require_once "ForcePathStyleListener.php";
                 $s3Client->addSubscriber(new \Aws\S3\ForcePathStyleStyleListener());
             }
             $s3Client->registerStreamWrapper();
         }
         self::$clients[$repoObject->getId()] = $s3Client;
     }
     return self::$clients[$repoObject->getId()];
 }
Пример #9
0
 /**
  * @param string   $key
  * @param DateTime $date
  */
 public function restoreByCopyingOldVersion($key, DateTime $date)
 {
     $versions = $this->getVersions($key);
     /** @var CMService_AwsS3Versioning_Response_Version $versionToRestore */
     $versionToRestore = Functional\first($versions, function (CMService_AwsS3Versioning_Response_Version $version) use($key, $date) {
         $isExactKeyMatch = $key === $version->getKey();
         $isModifiedBeforeOrAt = $date >= $version->getLastModified();
         return $isExactKeyMatch && $isModifiedBeforeOrAt;
     });
     $keepCurrentVersion = $versionToRestore && $versionToRestore->getIsLatest();
     if (!$keepCurrentVersion) {
         $hasNoPriorVersion = !$versionToRestore;
         $restoreVersionIsDeleteMarker = $versionToRestore && null === $versionToRestore->getETag() && null === $versionToRestore->getSize();
         if ($hasNoPriorVersion || $restoreVersionIsDeleteMarker) {
             $this->_client->deleteObject(array('Bucket' => $this->_bucket, 'Key' => $key));
         } else {
             $this->_client->copyObject(array('Bucket' => $this->_bucket, 'CopySource' => urlencode($this->_bucket . '/' . $key) . '?versionId=' . $versionToRestore->getId(), 'Key' => $key));
         }
     }
 }
Пример #10
0
 /**
  * @param string $name
  * @return Aws
  */
 public function __get($name)
 {
     switch ($name) {
         case 'sqs':
             if (empty($this->sqs_client)) {
                 $this->sqs_client = Aws\Sqs\SqsClient::factory(array('key' => $this->CI->config->item('sqs_access_key_id'), 'secret' => $this->CI->config->item('sqs_secret_key'), 'region' => $this->CI->config->item('aws_region')));
             }
             $this->client = $this->sqs_client;
             break;
         case 's3':
             if (empty($this->s3_client)) {
                 $this->s3_client = Aws\S3\S3Client::factory(array('key' => $this->CI->config->item('s3_access_key_id'), 'secret' => $this->CI->config->item('s3_secret_key'), 'region' => $this->CI->config->item('aws_region')));
             }
             $this->client = $this->s3_client;
             break;
         default:
             break;
     }
     return $this;
 }
Пример #11
0
 /**
  * Restores an item from AWS Glacier using the provided bucket name and key.
  * 
  * @param string $sBucket
  * @param string $sKey
  * @param integer $iDays
  * @return string
  */
 public function restoreItem($sBucket, $sKey, $iDays = 1)
 {
     $oS3Client = $this->oAwsClient->get(self::SERVICE_S3);
     //Filtering the days argument, must be a non zero int
     $iFilteredDays = \is_int($iDays) && $iDays > 0 ? $iDays : 1;
     $aReturns = array();
     $aReturns['status'] = 500;
     $aReturns['RequestId'] = '';
     $aReturns['message'] = 'Restore has failed for ' . $sKey;
     try {
         $oGuzzle = $oS3Client->restoreObject(array('Bucket' => $sBucket, 'Key' => $sKey, 'Days' => $iFilteredDays));
         if (\is_string($oGuzzle->get('RequestId')) && $oGuzzle->get('RequestId') != '') {
             $aReturns['status'] = 200;
             $aReturns['RequestId'] = $oGuzzle->get('RequestId');
             $aReturns['message'] = 'Restore completed for ' . $sKey;
         }
     } catch (\Exception $oExp) {
         $aReturns['message'] = 'Restore has failed for ' . $sKey . '. ' . $oExp->getMessage();
     }
     return \json_encode($aReturns);
 }
Пример #12
0
 private function s3()
 {
     $amazon_option = get_option(PREFIX_AS3B . 'setting');
     if ($amazon_option) {
         require_once main::getPluginDir() . '/libs/classes/aws-autoloader.php';
         try {
             $dir = BACKUP_DIR . '/' . $this->params['name'];
             $credentials = new Aws\Common\Credentials\Credentials($amazon_option['access_key_id'], $amazon_option['secret_access_key']);
             $client = Aws\S3\S3Client::factory(array('credentials' => $credentials));
             main::log(lang::get("Get Files for Resore Backup", false));
             $keys = $client->listObjects(array('Bucket' => $amazon_option['bucket'], 'Prefix' => $this->params['name']))->getIterator();
             //->getPath('Contents/*/Key');
             if (isset($keys['Contents'])) {
                 $n = count($keys['Contents']);
                 main::mkdir($dir);
                 main::log(lang::get("Start Download files with Amazon S3", false));
                 for ($i = 0; $i < $n; $i++) {
                     $path = explode("/", $keys['Contents'][$i]['Key']);
                     if (isset($path[0]) && isset($path[1]) && !empty($path[1])) {
                         $result = $client->getObject(array('Bucket' => $amazon_option['bucket'], 'Key' => $keys['Contents'][$i]['Key'], 'SaveAs' => BACKUP_DIR . '/' . $keys['Contents'][$i]['Key']));
                         main::log(str_replace("%s", $keys['Contents'][$i]['Key'], lang::get("Download file - %s", false)));
                     }
                 }
                 main::log(lang::get("End downloads files with Amazon S3", false));
                 $this->local();
                 if (is_dir($dir)) {
                     main::remove($dir);
                 }
             } else {
                 $this->setError(lang::get("Error, in downloads with Amazon S3", false));
             }
         } catch (Exception $e) {
             $this->setError($e->getMessage());
         } catch (S3Exception $e) {
             $this->setError($e->getMessage());
         }
     } else {
         $this->setError(lang::get('Error: Data is not exist for send backup files to Amazon S3. Please type your Data in the Settings form', false));
     }
 }
function getTemplates($user)
{
    require '../vendor/autoload.php';
    $prefixstr = $user . '/';
    $s3 = Aws\S3\S3Client::factory();
    $filenamearray = array();
    $objects = $s3->getIterator('ListObjects', array('Bucket' => 'cpgrantstemplates', 'Prefix' => $prefixstr));
    foreach ($objects as $object) {
        array_push($filenamearray, $object['Key']);
    }
    echo json_encode($filenamearray);
}
$link = mysqli_connect($endpoint, "controller", "letmein888", "customerrecords") or die("Error " . mysqli_error($link));
/* Checking the database connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit;
}
$uploaddir = '/tmp/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$backup = uniqid("dbBackup", false);
$backupfile = $uploaddir . $backup . '.' . 'sql';
$dbuser = "******";
$dbpass = "******";
echo $dbuser;
echo $dbpass;
$sqlcommand = "mysqldump --user={$dbuser} --password={$dbpass} --host={$endpoint} customerrecords > {$backupfile}";
echo $sqlcommand;
exec($sqlcommand);
$s3 = new Aws\S3\S3Client(['version' => 'latest', 'region' => 'us-east-1']);
$bucket = uniqid("database-backup-", false);
# AWS PHP SDK version 3 create bucket
$result = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $bucket]);
$s3->waitUntil('BucketExists', array('Bucket' => $bucket));
# PHP version 3
$result = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Key' => $backupfile, 'SourceFile' => $backupfile]);
$expiration = $s3->putBucketLifecycleConfiguration(['Bucket' => $bucket, 'LifecycleConfiguration' => ['Rules' => [['Expiration' => ['Date' => '2015-12-25'], 'Prefix' => ' ', 'Status' => 'Enabled']]]]);
$sqlurl = $result['ObjectURL'];
echo $sqlurl;
echo "Database backup created successfully and stored in the s3 bucket.";
?>

Пример #15
0
<?php

/**
 * Loads test fixtures into S3
 */
date_default_timezone_set('Europe/Prague');
ini_set('display_errors', true);
error_reporting(E_ALL);
$basedir = dirname(__DIR__);
require_once $basedir . '/vendor/autoload.php';
$client = new \Aws\S3\S3Client(['region' => getenv('AWS_REGION'), 'version' => '2006-03-01', 'credentials' => ['key' => getenv('AWS_ACCESS_KEY'), 'secret' => getenv('AWS_SECRET_KEY')]]);
// Where the files will be source from
$source = $basedir . '/tests/_data/csv-import';
// Where the files will be transferred to
$bucket = getenv('AWS_S3_BUCKET');
$dest = 's3://' . $bucket;
// clear bucket
$result = $client->listObjects(['Bucket' => $bucket, 'Delimiter' => '/']);
$objects = $result->get('Contents');
if ($objects) {
    $client->deleteObjects(['Bucket' => $bucket, 'Delete' => ['Objects' => array_map(function ($object) {
        return ['Key' => $object['Key']];
    }, $objects)]]);
}
// Create a transfer object.
$manager = new \Aws\S3\Transfer($client, $source, $dest, ['debug' => true]);
// Perform the transfer synchronously.
$manager->transfer();
// Create manifests
$manifest = ['entries' => [['url' => sprintf("s3://%s/tw_accounts.csv", $bucket), 'mandatory' => true]]];
$client->putObject(['Bucket' => $bucket, 'Key' => '01_tw_accounts.csv.manifest', 'Body' => json_encode($manifest)]);
<?php

require '/app/vendor/autoload.php';
$s3 = Aws\S3\S3Client::factory();
$params = array('Bucket' => 'cpgrantsdocs', 'Key' => $_POST['id'], 'SaveAs' => 'localdoc.docx');
$result = $s3->getObject($params);
$result = $s3->deleteObject(array('Bucket' => 'cpgrantsdocs', 'Key' => $_POST['id']));
$filename = $_POST['filename'];
$file_url = 'localdoc.docx';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=" . $filename . ".docx");
readfile($file_url);
Пример #17
0
 * See the License for the specific language governing permissions and
 * limitations under the License.
**/
// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';
/*
 If you instantiate a new client for Amazon Simple Storage Service (S3) with
 no parameters or configuration, the AWS SDK for PHP will look for access keys
 in the following order: environment variables, ~/.aws/credentials file, then finally
 IAM Roles for Amazon EC2 Instances. The first set of credentials the SDK is able
 to find will be used to instantiate the client.

 For more information about this interface to Amazon S3, see:
 http://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/basic-usage.html#creating-a-client
*/
$s3 = new Aws\S3\S3Client(['version' => '2006-03-01', 'region' => 'eu-central-1']);
/*
 Everything uploaded to Amazon S3 must belong to a bucket. These buckets are
 in the global namespace, and must have a unique name.

 For more information about bucket name restrictions, see:
 http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
*/
$bucket = 'kuchy';
$filename = 'orange-pi-one-pocitac-raspberry-pi-nestandard2.jpg';
$imgUrl = 'http://ipravda.sk/res/2016/01/30/thumbs/' . $filename;
$img = file_get_contents($imgUrl);
/*
 Files in Amazon S3 are called "objects" and are stored in buckets. A specific
 object is referred to by its key (i.e., name) and holds data. Here, we create
 a new object with the key "hello_world.txt" and content "Hello World!".
system("mkdir /tmp/{$now}/");
foreach ($alldb as $db) {
    $cmd = "mysqldump {$db} -h " . getDbHost() . " -u controller -pilovebunnies > /tmp/{$now}/{$db}.sql";
    deb("Doing: {$cmd}");
    system($cmd);
}
// ********************************
// gzip databases
// ********************************
foreach ($alldb as $db) {
    system("gzip /tmp/{$now}/{$db}.sql");
}
// ********************************
// Upload the files to S3
// ********************************
$s3 = new Aws\S3\S3Client(['version' => 'latest', 'region' => 'us-east-1']);
$bucket = strtolower('phpmys3backup' . '-' . $now);
deb("Creating Bucket {$bucket}");
$create_bucket_response = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $bucket]);
deb("created bucket {$bucket}");
deb("bucket created - doing file add");
foreach ($alldb as $db) {
    $filename = "{$db}.sql.gz";
    $path = "/tmp/{$now}/";
    $uploadfile = $path . $filename;
    $result = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Key' => $uploadfile, 'SourceFile' => $uploadfile]);
    $objUrl = $result['ObjectURL'];
    deb("Uploaded Object URL: {$objUrl}");
}
// ********************************
// Cleanup the local filesystem
<?php

session_start();
if (!isset($_SESSION['UserData']['Username'])) {
    header("location:login.php");
}
require 'lib/aws-autoloader.php';
$msg = "";
$s3 = Aws\S3\S3Client::factory(['credentials' => array('key' => '*********************', 'secret' => '*********************'), 'region' => 'eu-central-1', 'version' => 'latest']);
if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $name = $file['name'];
    $tmp_name = $file['tmp_name'];
    $tmp_file_path = "files/{$name}";
    move_uploaded_file($tmp_name, $tmp_file_path);
    $result = $s3->putObject(['Bucket' => 'bauboxbucket', 'Key' => $name, 'Body' => fopen($tmp_file_path, 'rb'), 'ACL' => 'public-read']);
    if ($result) {
        $msg = "<span><strong>Success!</strong> File uploaded succefuly</span>";
    } else {
        $msg = "<span style='color:red'>ERROR</span>";
    }
}
$iterator = $s3->getIterator('ListObjects', ['Bucket' => "bauboxbucket"]);
if (isset($_GET["delete"])) {
    $key = $_GET["delete"];
    $result = $s3->deleteObject(array('Bucket' => 'bauboxbucket', 'Key' => $key));
    if ($result) {
        $msg = "<span><strong></strong> File deleted succefuly</span>";
    }
    unlink("files/" . $key);
}
Пример #20
0
 public static function delete_backup()
 {
     if (isset($_POST['backup-name']) && isset($_POST['backup-type'])) {
         if ($_POST['backup-type'] == 'local') {
             self::remove(BACKUP_DIR . "/" . $_POST['backup-name']);
         } elseif ($_POST['backup-type'] == 's3') {
             $amazon_option = get_option(PREFIX_AS3B . 'setting');
             if ($amazon_option) {
                 require_once self::getPluginDir() . '/libs/classes/aws-autoloader.php';
                 $credentials = new Aws\Common\Credentials\Credentials($amazon_option['access_key_id'], $amazon_option['secret_access_key']);
                 $client = Aws\S3\S3Client::factory(array('credentials' => $credentials));
                 try {
                     $keys = $client->listObjects(array('Bucket' => $amazon_option['bucket'], 'Prefix' => $_POST['backup-name']))->getIterator();
                     if (isset($keys['Contents'])) {
                         $n = count($keys['Contents']);
                         for ($i = 0; $i < $n; $i++) {
                             $client->deleteObject(array('Bucket' => $amazon_option['bucket'], 'Key' => $keys['Contents'][$i]['Key']));
                         }
                     }
                 } catch (Exception $e) {
                     self::setError($e->getMessage());
                 } catch (S3Exception $e) {
                     self::setError($e->getMessage());
                 }
             }
         }
     }
     Header("location: " . admin_url('admin.php?page=amazon-s3-backup'));
 }
Пример #21
0
//Creating a dump of the RDS database instance
$db = 'usnehadb';
$username = '******';
$password = '******';
$dbclient = new Aws\Rds\RdsClient(['version' => 'latest', 'region' => 'us-west-2']);
$result = $dbclient->describeDBInstances(['DBInstanceIdentifier' => 'usneha']);
$endpoint = $result['DBInstances'][0]['Endpoint']['Address'];
$link = mysqli_connect($endpoint, "username", "password", "usnehadb") or die("Error " . mysqli_error($link));
// making a folder for storing backup
mkdir("/tmp/dbDump");
// path for backup folder
$dumpPath = '/tmp/dbDump/';
$fname = uniqid("dbdump", false);
$finalPath = $dumpPath . $fname . '.' . sql;
// found this line in stackoverflow
$sql = "mysqldump --user={$username} --password={$password} --host={$endpoint} {$db} > {$finalPath}";
exec($sql);
$bucketname = uniqid("dbdump", false);
$s3 = new Aws\S3\S3Client(['version' => 'latest', 'region' => 'us-west-2']);
# AWS PHP SDK version 3 create bucket
$result = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $bucketname]);
$key = $fname . '.' . sql;
# PHP version 3
$result = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucketname, 'Key' => $key, 'SourceFile' => $finalPath]);
// reference: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html#putbucketlifecycleconfiguration
$result = $s3->putBucketLifecycleConfiguration(['Bucket' => $bucketname, 'LifecycleConfiguration' => ['Rules' => [['Expiration' => ['Days' => 1], 'NoncurrentVersionExpiration' => ['NoncurrentDays' => 1], 'Prefix' => ' ', 'Status' => 'Enabled']]]]);
mysql_close($link);
echo "Create db dump in s3!";
?>
</html>
Пример #22
0
 public static function getBackupsInAmazon($setting)
 {
     require_once dirname(__FILE__) . '/modules/aws-autoloader.php';
     $credentials = new Aws\Common\Credentials\Credentials($setting['access_key_id'], $setting['secret_access_key']);
     $client = Aws\S3\S3Client::factory(array('credentials' => $credentials));
     $data = array('data' => array(), 'md5' => md5(print_r(array(), 1)));
     try {
         $project = self::getNameProject();
         $keys = $client->listObjects(array('Bucket' => $setting['bucket'], 'Prefix' => $project . '-db'))->getIterator();
         //->getPath('Contents/*/Key');
         if (isset($keys['Contents'])) {
             $n = count($keys['Contents']);
             $j = 0;
             $backups = array();
             for ($i = 0; $i < $n; $i++) {
                 if (isset($keys['Contents'][$i]['Key'])) {
                     $backup = explode('/', $keys['Contents'][$i]['Key']);
                     if (isset($backup[0]) && isset($backup[1]) && !empty($backup[1])) {
                         if (!isset($backups[$backup[0]])) {
                             $backups[$backup[0]] = $j;
                             $data['data'][$j]['name'] = $backup[0];
                             $data['data'][$j]['dt'] = parent::getDateInName($backup[0]);
                             $data['data'][$j]['size'] = $keys['Contents'][$i]['Size'];
                             $data['data'][$j]['files'] = $backup[1];
                             $data['data'][$j]['type'] = 's3';
                             $data['data'][$j]['count'] = 1;
                             $j++;
                         } else {
                             $data['data'][$backups[$backup[0]]]['files'] .= ',' . $backup[1];
                             $data['data'][$backups[$backup[0]]]['size'] += $keys['Contents'][$i]['Size'];
                             $data['data'][$backups[$backup[0]]]['count'] += 1;
                         }
                     }
                 }
             }
         }
     } catch (\Aws\S3\Exception\S3Exception $e) {
         return $data;
     }
     return $data;
 }
Пример #23
0
 /**
  * @return Aws\S3\S3Client
  */
 public function s3()
 {
     if (!empty($this->s3)) {
         return $this->s3;
     }
     $params = array('version' => 'latest');
     if ($this->key && $this->secret) {
         $params['credentials']['key'] = $this->key;
         $params['credentials']['secret'] = $this->secret;
     }
     if ($this->region) {
         $params['signature'] = 'v4';
         $params['region'] = $this->region;
     }
     if (defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT')) {
         $proxy_auth = '';
         $proxy_address = WP_PROXY_HOST . ':' . WP_PROXY_PORT;
         if (defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD')) {
             $proxy_auth = WP_PROXY_USERNAME . ':' . WP_PROXY_PASSWORD . '@';
         }
         $params['request.options']['proxy'] = $proxy_auth . $proxy_address;
     }
     $params = apply_filters('s3_uploads_s3_client_params', $params);
     $this->s3 = Aws\S3\S3Client::factory($params);
     return $this->s3;
 }
} else {
    echo "post empty";
}
$uploaddir = '/tmp/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
print '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
require 'vendor/autoload.php';
$s3 = new Aws\S3\S3Client(['version' => 'latest', 'region' => 'us-east-1']);
#print_r($s3);
$bucket = uniqid("Sneha", false);
#$result = $s3->createBucket(array(
#    'Bucket' => $bucket
#));
#
## AWS PHP SDK version 3 create bucket
$result = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $bucket]);
#print_r($result);
$result = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Key' => $uploadfile, 'ContentType' => $_FILES['userfile']['type'], 'Body' => fopen($uploadfile, 'r+')]);
$url = $result['ObjectURL'];
echo $url;
$rds = new Aws\Rds\RdsClient(['version' => 'latest', 'region' => 'us-east-1']);
$result = $rds->describeDBInstances(array('DBInstanceIdentifier' => 'db1'));
$endpoint = $result['DBInstances'][0]['Endpoint']['Address'];
Пример #25
0
 /**
  * @param string $args
  */
 public function edit_ajax($args = '')
 {
     $error = '';
     $buckets_list = array();
     if (is_array($args)) {
         $ajax = FALSE;
     } else {
         if (!current_user_can('backwpup_jobs_edit')) {
             wp_die(-1);
         }
         check_ajax_referer('backwpup_ajax_nonce');
         $args['s3accesskey'] = sanitize_text_field($_POST['s3accesskey']);
         $args['s3secretkey'] = sanitize_text_field($_POST['s3secretkey']);
         $args['s3bucketselected'] = sanitize_text_field($_POST['s3bucketselected']);
         $args['s3base_url'] = esc_url_raw($_POST['s3base_url']);
         $args['s3region'] = sanitize_text_field($_POST['s3region']);
         $ajax = TRUE;
     }
     echo '<span id="s3bucketerror" style="color:red;">';
     if (!empty($args['s3accesskey']) && !empty($args['s3secretkey'])) {
         try {
             $s3 = Aws\S3\S3Client::factory(array('key' => $args['s3accesskey'], 'secret' => BackWPup_Encryption::decrypt($args['s3secretkey']), 'region' => $args['s3region'], 'base_url' => $this->get_s3_base_url($args['s3region'], $args['s3base_url']), 'scheme' => 'https', 'ssl.certificate_authority' => BackWPup::get_plugin_data('cacert')));
             $buckets = $s3->listBuckets();
             if (!empty($buckets['Buckets'])) {
                 $buckets_list = $buckets['Buckets'];
             }
             while (!empty($vaults['Marker'])) {
                 $buckets = $s3->listBuckets(array('marker' => $buckets['Marker']));
                 if (!empty($buckets['Buckets'])) {
                     $buckets_list = array_merge($buckets_list, $buckets['Buckets']);
                 }
             }
         } catch (Exception $e) {
             $error = $e->getMessage();
         }
     }
     if (empty($args['s3accesskey'])) {
         _e('Missing access key!', 'backwpup');
     } elseif (empty($args['s3secretkey'])) {
         _e('Missing secret access key!', 'backwpup');
     } elseif (!empty($error) && $error == 'Access Denied') {
         echo '<input type="text" name="s3bucket" id="s3bucket" value="' . esc_attr($args['s3bucketselected']) . '" >';
     } elseif (!empty($error)) {
         echo esc_html($error);
     } elseif (!isset($buckets) || count($buckets['Buckets']) < 1) {
         _e('No bucket found!', 'backwpup');
     }
     echo '</span>';
     if (!empty($buckets_list)) {
         echo '<select name="s3bucket" id="s3bucket">';
         foreach ($buckets_list as $bucket) {
             echo "<option " . selected($args['s3bucketselected'], esc_attr($bucket['Name']), FALSE) . ">" . esc_attr($bucket['Name']) . "</option>";
         }
         echo '</select>';
     }
     if ($ajax) {
         die;
     }
 }
Пример #26
0
 /**
  * Constructor - if you're not using the class statically
  *
  * @param string $accessKey Access key
  * @param string $secretKey Secret key
  * @param boolean $useSSL Enable SSL
  * @param string|boolean $sslCACert - certificate authority (true = bundled Guzzle version; false = no verify, 'system' = system version; otherwise, path)
  * @return void
  */
 public function __construct($accessKey = null, $secretKey = null, $useSSL = true, $sslCACert = true, $endpoint = null)
 {
     if ($accessKey !== null && $secretKey !== null) {
         $this->setAuth($accessKey, $secretKey);
     }
     $this->useSSL = $useSSL;
     $this->sslCACert = $sslCACert;
     $opts = array('key' => $accessKey, 'secret' => $secretKey, 'scheme' => $useSSL ? 'https' : 'http');
     if ($endpoint) {
         // Can't specify signature v4, as that requires stating the region - which we don't necessarily yet know.
         $this->endpoint = $endpoint;
         $opts['endpoint'] = $endpoint;
     } else {
         // Using signature v4 requires a region. Also, some regions (EU Central 1, China) require signature v4 - and all support it, so we may as well use it if we can.
         $opts['signature'] = 'v4';
         $opts['region'] = $this->region;
     }
     if ($useSSL) {
         $opts['ssl.certificate_authority'] = $sslCACert;
     }
     $this->client = Aws\S3\S3Client::factory($opts);
 }
<?php

/**
 * Loads test fixtures into S3
 */
date_default_timezone_set('Europe/Prague');
ini_set('display_errors', true);
error_reporting(E_ALL);
$basedir = dirname(__DIR__);
require_once $basedir . '/vendor/autoload.php';
$client = new \Aws\S3\S3Client(['region' => 'us-east-1', 'version' => '2006-03-01', 'credentials' => ['key' => getenv('AWS_ACCESS_KEY'), 'secret' => getenv('AWS_SECRET_KEY')]]);
$client->getObject(['Bucket' => 'keboola-configs', 'Key' => 'drivers/snowflake/snowflake_linux_x8664_odbc.2.12.87.tgz', 'SaveAs' => './snowflake_linux_x8664_odbc.tgz']);
$rds = new Aws\Rds\RdsClient(['version' => 'latest', 'region' => 'us-east-1']);
$resultrdb = $rds->describeDBInstances(array('DBInstanceIdentifier' => 'mp1SKread-replica'));
$endpointrdb = $resultrdb['DBInstances'][0]['Endpoint']['Address'];
echo "============\n" . $endpointrdb . "================";
$linkrdb = mysqli_connect($endpointrdb, "testconnection1", "testconnection1", "Project1");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit;
} else {
    echo "Connection to RDB Success";
}
$backupFile = '/tmp/FinalProjectDB' . date("Y-m-d-H-i-s") . '.gz';
$command = "mysqldump --opt -h {$endpointrdb} -u testconnection1 -ptestconnection1 Project1 | gzip > {$backupFile}";
exec($command);
echo "success";
$s3 = new Aws\S3\S3Client(['version' => 'latest', 'region' => 'us-east-1']);
$bucket = 'snehatestproject-' . rand() . '-dbdump';
if (!$s3->doesBucketExist($bucket)) {
    $result = $s3->createBucket(['ACL' => 'public-read', 'Bucket' => $bucket]);
    $s3->waitUntil('BucketExists', array('Bucket' => $bucket));
    echo "{$bucket} Created Successfully";
}
$result = $s3->putObject(['ACL' => 'public-read', 'Bucket' => $bucket, 'Key' => $backupFile, 'SourceFile' => $backupFile]);
$result = $s3->putBucketLifecycleConfiguration(['Bucket' => $bucket, 'LifecycleConfiguration' => ['Rules' => [['Expiration' => ['Days' => 2], 'NoncurrentVersionExpiration' => ['NoncurrentDays' => 2], 'Prefix' => '', 'Status' => 'Enabled']]]]);
echo "backup success";
$url = $result['ObjectURL'];
echo $url;
$urlintro = "index.php";
header('Location: ' . $urlintro, true);
die;
$linkrdb->close();
Пример #29
-1
 public function testCredentialsGetUpdated()
 {
     $credentials = new Credentials('access-key-one', 'secret');
     $signature = $this->getMock('Aws\\Common\\Signature\\SignatureV4');
     $config = new Collection();
     $client = new \Aws\S3\S3Client($credentials, $signature, $config);
     $listener = new SignatureListener($credentials, $signature);
     $client->addSubscriber($listener);
     $this->assertEquals('access-key-one', $this->readAttribute($listener, 'credentials')->getAccessKeyId());
     $client->setCredentials(new Credentials('access-key-two', 'secret'));
     $this->assertEquals('access-key-two', $this->readAttribute($listener, 'credentials')->getAccessKeyId());
 }
Пример #30
-1
<?php

require __DIR__ . '/artifacts/aws.phar';
$client = Aws\S3\S3Client::factory(['endpoint' => 'http://mtmss.com', 'ssl.certificate_authority' => false, 'key' => '*', 'secret' => '*']);
echo 'Version=' . Aws\Common\Aws::VERSION;
# $client->createBucket(array('Bucket' => 'mybucket-php1'));