getObject() public static method

Get an object
public static getObject ( string $bucket, string $uri, mixed $saveTo = false ) : mixed
$bucket string Bucket name
$uri string Object URI
$saveTo mixed Filename or resource to write to
return mixed
 /**
  * @inheritDoc BaseAssetSourceType::getLocalCopy()
  *
  * @param AssetFileModel $file
  *
  * @return mixed
  */
 public function getLocalCopy(AssetFileModel $file)
 {
     $location = AssetsHelper::getTempFilePath($file->getExtension());
     $this->_prepareForRequests();
     $this->_s3->getObject($this->getSettings()->bucket, $this->_getS3Path($file), $location);
     return $location;
 }
Beispiel #2
0
 function process_s3_copy($s3file, $accesskey, $secretkey, $bucket, $directory)
 {
     pb_backupbuddy::set_greedy_script_limits();
     require_once pb_backupbuddy::plugin_path() . '/lib/s3/s3.php';
     $s3 = new S3($accesskey, $secretkey);
     $destination_file = ABSPATH . 'wp-content/uploads/backupbuddy_backups/' . $s3file;
     if (file_exists($destination_file)) {
         $destination_file = str_replace('backup-', 'backup_copy_' . pb_backupbuddy::random_string(5) . '-', $destination_file);
     }
     $s3->getObject($bucket, $directory . $s3file, $destination_file);
 }
Beispiel #3
0
 public static function get($file, $type, $output = false)
 {
     global $globals;
     $uri = "{$type}/{$file}";
     S3::setAuth($globals['Amazon_access_key'], $globals['Amazon_secret_key']);
     if ($object = @S3::getObject($globals['Amazon_S3_media_bucket'], $uri, $output)) {
         return $object;
     }
     syslog(LOG_NOTICE, "Meneame, failed to get {$uri} from S3");
     @unlink($output);
     return false;
 }
Beispiel #4
0
 public static function downloadFile(array $localFileItemInfo, $savePath, $filename = false)
 {
     Zotero_S3::requireLibrary();
     S3::setAuth(Z_CONFIG::$S3_ACCESS_KEY, Z_CONFIG::$S3_SECRET_KEY);
     if (!file_exists($savePath)) {
         throw new Exception("Path '{$savePath}' does not exist");
     }
     if (!is_dir($savePath)) {
         throw new Exception("'{$savePath}' is not a directory");
     }
     $response = S3::getObject(Z_CONFIG::$S3_BUCKET, self::getPathPrefix($localFileItemInfo['hash'], $localFileItemInfo['zip']) . $localFileItemInfo['filename'], $savePath . "/" . ($filename ? $filename : $localFileItemInfo['filename']));
     return $response;
 }
Beispiel #5
0
 public static function get($file, $type, $output = false)
 {
     global $globals;
     $uri = "{$type}/{$file}";
     S3::setAuth($globals['Amazon_access_key'], $globals['Amazon_secret_key']);
     $object = @S3::getObject($globals['Amazon_S3_media_bucket'], $uri, $output);
     $lastHTTPCode = $object->code;
     if ($object) {
         return $object;
     }
     // syslog(LOG_NOTICE, "Meneame, failed to get $uri from S3 to $output code: " . S3::$lastHTTPCode);
     @unlink($output);
     return false;
 }
Beispiel #6
0
 /**
  * Tests S3
  *
  * @param string $error
  * @return boolean
  */
 function test(&$error)
 {
     if (!parent::test($error)) {
         return false;
     }
     $string = 'test_s3_' . md5(time());
     if (!$this->_init($error)) {
         return false;
     }
     $this->_set_error_handler();
     $buckets = @$this->_s3->listBuckets();
     if ($buckets === false) {
         $error = sprintf('Unable to list buckets (%s).', $this->_get_last_error());
         $this->_restore_error_handler();
         return false;
     }
     if (!in_array($this->_config['bucket'], (array) $buckets)) {
         $error = sprintf('Bucket doesn\'t exist: %s.', $this->_config['bucket']);
         $this->_restore_error_handler();
         return false;
     }
     if (!@$this->_s3->putObjectString($string, $this->_config['bucket'], $string, S3::ACL_PUBLIC_READ)) {
         $error = sprintf('Unable to put object (%s).', $this->_get_last_error());
         $this->_restore_error_handler();
         return false;
     }
     if (!($object = @$this->_s3->getObject($this->_config['bucket'], $string))) {
         $error = sprintf('Unable to get object (%s).', $this->_get_last_error());
         $this->_restore_error_handler();
         return false;
     }
     if ($object->body != $string) {
         $error = 'Objects are not equal.';
         @$this->_s3->deleteObject($this->_config['bucket'], $string);
         $this->_restore_error_handler();
         return false;
     }
     if (!@$this->_s3->deleteObject($this->_config['bucket'], $string)) {
         $error = sprintf('Unable to delete object (%s).', $this->_get_last_error());
         $this->_restore_error_handler();
         return false;
     }
     $this->_restore_error_handler();
     return true;
 }
Beispiel #7
0
 /**
  * Tests S3
  *
  * @param string $error
  * @return boolean
  */
 function test(&$error)
 {
     $string = 'test_s3_' . md5(time());
     if (!$this->_init($error)) {
         return false;
     }
     $domain = $this->get_domain();
     if (!$domain) {
         $error = 'Empty domain.';
         return false;
     }
     if (gethostbyname($domain) == $domain) {
         $error = sprintf('Unable to resolve domain: %s.', $domain);
         return false;
     }
     $buckets = @$this->_s3->listBuckets();
     if (!$buckets) {
         $error = 'Unable to list buckets (check your credentials).';
         return false;
     }
     if (!in_array($this->_config['bucket'], (array) $buckets)) {
         $error = sprintf('Bucket doesn\'t exist: %s', $this->_config['bucket']);
         return false;
     }
     if (!@$this->_s3->putObjectString($string, $this->_config['bucket'], $string, S3::ACL_PUBLIC_READ)) {
         $error = 'Unable to put object.';
         return false;
     }
     if (!($object = @$this->_s3->getObject($this->_config['bucket'], $string))) {
         $error = 'Unable to get object.';
         return false;
     }
     if ($object->body != $string) {
         @$this->_s3->deleteObject($this->_config['bucket'], $string);
         $error = 'Objects are not equal.';
         return false;
     }
     if (!@$this->_s3->deleteObject($this->_config['bucket'], $string)) {
         $error = 'Unable to delete object.';
         return false;
     }
     return true;
 }
Beispiel #8
0
<?php

/*
CometChat
Copyright (c) 2016 Inscripts
License: https://www.cometchat.com/legal/license
*/
include_once dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . "config.php";
$file = preg_replace("/[^a-zA-Z0-9\\. ]/", "", $_GET['file']);
$file = str_replace(" ", "_", $file);
if (defined('AWS_STORAGE') && AWS_STORAGE == '1') {
    include_once dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . "functions" . DIRECTORY_SEPARATOR . "storage" . DIRECTORY_SEPARATOR . "s3.php";
    $s3 = new S3(AWS_ACCESS_KEY, AWS_SECRET_KEY);
    $filedata = $s3->getObject(AWS_BUCKET, $bucket_path . 'filetransfer/' . $file);
    $filesize = $filedata->headers['size'];
} else {
    $filepath = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'writable' . DIRECTORY_SEPARATOR . 'filetransfer' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $file;
    $filedata = file_exists($filepath);
    $filesize = filesize($filepath);
}
if ($filedata) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename=' . rawurldecode($_GET['unencryptedfilename']));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . $filesize);
    if (defined('AWS_STORAGE') && AWS_STORAGE == '1') {
        echo $filedata->body;
Beispiel #9
0
 public function downloadToPath($path)
 {
     //make directory.
     $dir = dirname($path);
     if (!file_exists($dir)) {
         mkdir($dir, 0777, true);
     }
     if (!is_writable($dir)) {
         return false;
     }
     //load up S3 for download
     $s3 = new S3(AMAZON_AWS_KEY, AMAZON_AWS_SECRET);
     $result = $s3->getObject($this->get('bucket'), $this->get('path'), $path);
     //did it work?
     if ($result !== false) {
         return true;
     }
     //fail :-/
     return false;
 }
Beispiel #10
0
    }
    $hash = $msg['h'];
    $salt = hash('sha256', $salts['file_hash'] . $hash);
    $password = substr(hash('sha256', $salt . $password), 0, 20);
    if ($pw === 'false' || $pw != 'false' && $pw == $password) {
        $years_to_live = 1;
        if (isset($msg['y'])) {
            $year_to_live = $msg['y'];
        }
        $bucket_name = $aws['bucket'];
        $s3 = new S3($aws['key'], $aws['secret']);
        $year = date('y', $tx['time']);
        $month = date('m', $tx['time']);
        $day = date('d', $tx['time']);
        $location = 'paid/' . $year . '/' . $month . '/' . $day . '/' . $txid . '.' . $file_extension;
        $obj = $s3->getObject($bucket_name, $location);
        header('Content-Type: ' . $type);
        echo $obj->body;
    } else {
        echo '<form action="" method="post">';
        if ($typed_pw) {
            echo '<p><strong>Wrong Password!</strong> Please try again...</p>';
        }
        echo '<input name="password" type="password" autocomplete="off" placeholder="enter password" />';
        echo '<input type="submit" value="submit" />';
        echo '</form>';
    }
} else {
    header("HTTP/1.0 404 Not Found");
    echo '404';
}
Beispiel #11
0
function copyqimage($key, $dest)
{
    if ($GLOBALS['filehandertypecfiles'] == 's3') {
        $s3 = new S3($GLOBALS['AWSkey'], $GLOBALS['AWSsecret']);
        $s3->getObject($GLOBALS['AWSbucket'], 'qimages/' . $key, $dest);
    } else {
        $base = rtrim(dirname(dirname(__FILE__)), '/\\') . '/assessment/qimages/';
        copy($base . $key, $dest);
    }
}
 public function get_file($hash)
 {
     $s3 = new S3('csub001050', 'studiomaiocchi', true, 'seewebstorage.it');
     $res = $s3->getObject('studiomaiocchistaging', $hash, false);
     return $res;
 }
Beispiel #13
0
/**
 * make sure backup file is local, download it and make it local if necessary
 */
function backup_restore_locate_file($id, $path)
{
    global $amp_conf;
    $path = trim($path, '/');
    $path = str_replace(array('..', ':'), '', trim($path, '/'));
    $path = escapeshellcmd($path);
    $s = backup_get_server($id);
    if (!$s) {
        return array('error_msg' => _('Backup Server not found!'));
    }
    //dest is where we gona put backup files pulled infrom other servers
    $dest = $amp_conf['ASTSPOOLDIR'] . '/tmp/' . 'backuptmp-s' . $id . '-' . time() . '-' . basename($path);
    switch ($s['type']) {
        case 'local':
            $s['path'] = backup__($s['path']);
            $path = $s['path'] . '/' . $path;
            break;
        case 'ftp':
            //subsitute variables if nesesary
            $s['host'] = backup__($s['host']);
            $s['port'] = backup__($s['port']);
            $s['user'] = backup__($s['user']);
            $s['password'] = backup__($s['password']);
            $s['path'] = backup__($s['path']);
            $ftp = ftp_connect($s['host'], $s['port']);
            if (ftp_login($ftp, $s['user'], $s['password'])) {
                ftp_pasv($ftp, $s['transfer'] == 'passive');
                if (ftp_get($ftp, $dest, $s['path'] . '/' . $path, FTP_BINARY)) {
                    $path = $dest;
                } else {
                    return array('error_msg' => _('Failed to retrieve file from server!'));
                }
                ftp_close($ftp);
            } else {
                dbug('ftp connect error');
            }
            break;
        case 'ssh':
            $s['path'] = backup__($s['path']);
            $s['user'] = backup__($s['user']);
            $s['host'] = backup__($s['host']);
            $cmd[] = fpbx_which('scp');
            $cmd[] = '-o StrictHostKeyChecking=no -i';
            $cmd[] = $s['key'];
            $cmd[] = '-P ' . $s['port'];
            $cmd[] = $s['user'] . '\\@' . $s['host'] . ':' . $s['path'] . '/' . $path;
            $cmd[] = $dest;
            exec(implode(' ', $cmd), $foo, $ret);
            unset($cmd);
            if ($ret === 0) {
                $path = $dest;
            } else {
                return array('error_msg' => _('Failed to retrieve file from server!'));
            }
            break;
        case 'awss3':
            $s['bucket'] = backup__($s['bucket']);
            $s['awsaccesskey'] = backup__($s['awsaccesskey']);
            $s['awssecret'] = backup__($s['awssecret']);
            $awss3 = new S3($s['awsaccesskey'], $s['awssecret']);
            dbug('S3 Path: ' . $path);
            dbug('S3 Dest: ' . $dest);
            if ($awss3->getObject($s['bucket'], $path, $dest) !== false) {
                $path = $dest;
            } else {
                return array('error_msg' => _('Failed to retrieve file from server!'));
            }
            break;
    }
    if (file_exists($path)) {
        return $path;
    } else {
        return array('error_msg' => _('File not found! ' . $path));
    }
}
<?php

$data = S3::getObject('resources', 'COE/sittings/' . $id . '.html');
return array('html' => @$data->body);
<?php

/**
 * Created by PhpStorm.
 * User: tomaszdrazewski
 * Date: 14/07/15
 * Time: 14:40
 */
$data = S3::getObject('resources', 'senat/stenogramy/' . $id . '.html');
return $data;
 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 #17
0
 public function getObject($bucket = '', $uri = '', $saveTo = false)
 {
     return S3::getObject($bucket, $uri, $saveTo);
 }
 /**
  * Finds the latest Backup archieve file from the Amazon S3 Bucket
  *
  * @return String
  * @access private
  * @see executeRestore()
  *
  */
 private function getBackupFileFromS3()
 {
     require_once 'S3.php';
     //Create a new Instance of the S3 Object
     $s3 = new S3($this->s3Config['accessKey'], $this->s3Config['secretKey'], false);
     $bucketContent = $s3->getBucket($this->s3Config['bucketName'], $this->databaseVars['database_name'] . "_backup");
     if (!empty($bucketContent)) {
         end($bucketContent);
         $keyname = key($bucketContent);
         // Save object to a file.
         $file = $s3->getObject($this->s3Config['bucketName'], $keyname, $this->backupDir . '/S3_' . $keyname);
         return $this->backupDir . '/S3_' . $keyname;
     } else {
         return NULL;
     }
 }
<?php

$data = S3::getObject('crawler', $id);
return array('html' => @$data->body);
Beispiel #20
0
         // No need to download anything, just create a folder entry
         $awsObjectInfo["name"] = substr($awsObjectInfo["name"], 0, -strlen('_$folder$'));
         echo 'Creating Marker for Folder ' . $awsObjectInfo["name"] . " on CloudFiles\n";
         $objMossoObject = $objMossoContainer->create_object($awsObjectInfo["name"]);
         $objMossoObject->content_type = $directoryType;
         // 'application/directory';
         // Get a Zero-byte file pointer
         $fp = @fopen("php://temp", "wb+");
         $objMossoObject->write($fp, 0);
         @fclose($fp);
         continue;
     }
     // Get object into a TMP file
     $tmpFileName = tempnam(sys_get_temp_dir(), 'S3toMosso');
     echo 'Downloading ' . $awsObjectInfo["name"] . " from Amazon S3 to {$tmpFileName}\n";
     $objS3->getObject($awsBucketName, $awsObjectInfo["name"], $tmpFileName);
     // Send Object to Mosso
     echo 'Creating object ' . $awsObjectInfo["name"] . " in container {$mossoContainerName}\n";
     $objMossoObject = $objMossoContainer->create_object($awsObjectInfo["name"]);
     try {
         $objMossoObject->_guess_content_type($tmpFileName);
     } catch (BadContentTypeException $e) {
         // Get the content type from Amazon
         $info = $objS3->getObjectInfo($awsBucketName, $awsObjectInfo["name"], true);
         $objMossoObject->content_type = $info['type'];
     }
     echo 'Uploading ' . $awsObjectInfo["name"] . ' to Cloud Files Server' . "\n";
     $objMossoObject->load_from_filename($tmpFileName);
     // Remove the TEMP file
     unlink($tmpFileName);
 }
$images = $s3->getBucket($bucket, $imgPrefix);
$imgNumber = 1;
$totalImgs = count($images);
echo 'Number of images: ', $totalImgs, "\n";
if (!$totalImgs) {
    exit('No images in the bucket');
}
$_reuploadThumbs = $overwriteThumbs || $compareThumbsBySize;
$images = array_keys($images);
foreach ($images as $image) {
    echo $image, ' (', $imgNumber++, ' of ', $totalImgs, ')', "\n";
    if (!file_exists($image) || $redownloadImages) {
        //Create directories for the image
        createDirectory(substr($image, 0, $imgPathLen));
        for ($i = 1; $i <= MAX_TRIES; $i++) {
            if ($s3->getObject($bucket, $image, $image) !== false) {
                break;
            }
            if ($i == MAX_TRIES) {
                echo 'Failed to download ', $image, "\n";
                if (file_exists($image)) {
                    unlink($image);
                }
                //Go to next image
                continue 2;
            }
        }
    } else {
        echo 'File ', $image, ' was already downloaded', "\n";
    }
    $dispersionPath = substr($image, $imgPrefixLen);
 public function save_as($key, $version)
 {
     if ($this->error) {
         return $this->getDebug() ? call_user_func_array('error', $this->error) : array();
     }
     if (!($key && $version)) {
         return $this->getDebug() ? error('OrmImageUploader 錯誤!', '參數錯誤,請檢查 save_as 函式參數!', '請程式設計者確認狀況!') : array();
     }
     if (!($versions = ($versions = $this->getVersions()) ? $versions : $this->configs['default_version'])) {
         return $this->getDebug() ? error('OrmImageUploader 錯誤!', 'Versions 格式錯誤,請檢查 getVersions () 或者 default_version!', '預設值 default_version 請檢查 config/system/orm_uploader.php 設定檔!') : array();
     }
     if (in_array($key, $keys = array_keys($versions))) {
         return $this->getDebug() ? error('OrmImageUploader 錯誤!', '已經有相符合的 key 名稱,key:' . $key, '目前的 key 有:' . implode(', ', $keys)) : array();
     }
     switch ($this->getDriver()) {
         case 'local':
             foreach ($versions as $ori_key => $ori_version) {
                 if (is_readable(FCPATH . implode(DIRECTORY_SEPARATOR, $ori_path = array_merge($this->getBaseDirectory(), $this->getSavePath(), array($ori_key . $this->configs['separate_symbol'] . ($name = $this->getValue())))))) {
                     break;
                 }
             }
             if (!$ori_path) {
                 return $this->getDebug() ? error('OrmImageUploader 錯誤!', '沒有任何的檔案可以被使用!', '請確認 getVersions () 函式內有存在的檔案可被另存!', '請程式設計者確認狀況!') : array();
             }
             if (!file_exists(FCPATH . implode(DIRECTORY_SEPARATOR, $path = array_merge($this->getBaseDirectory(), $this->getSavePath())))) {
                 $oldmask = umask(0);
                 @mkdir(FCPATH . implode(DIRECTORY_SEPARATOR, $path), 0777, true);
                 umask($oldmask);
             }
             if (!is_writable(FCPATH . implode(DIRECTORY_SEPARATOR, $path))) {
                 return $this->getDebug() ? error('OrmImageUploader 錯誤!', '資料夾不能儲存!路徑:' . $path, '請程式設計者確認狀況!') : '';
             }
             try {
                 $image = ImageUtility::create(FCPATH . implode(DIRECTORY_SEPARATOR, $ori_path), null);
                 $path = array_merge($path, array($key . $this->configs['separate_symbol'] . $name));
                 if ($this->_utility($image, FCPATH . implode(DIRECTORY_SEPARATOR, $path), $key, $version)) {
                     return $path;
                 } else {
                     return array();
                 }
             } catch (Exception $e) {
                 return $this->getDebug() ? call_user_func_array('error', $e->getMessages()) : '';
             }
             break;
         case 's3':
             if (!@S3::getObject($this->getS3Bucket(), implode(DIRECTORY_SEPARATOR, array_merge($path = array_merge($this->getBaseDirectory(), $this->getSavePath()), array($fileName = array_shift(array_keys($versions)) . $this->configs['separate_symbol'] . ($name = $this->getValue())))), FCPATH . implode(DIRECTORY_SEPARATOR, $fileName = array_merge($this->getTempDirectory(), array($fileName))))) {
                 return $this->getDebug() ? error('OrmImageUploader 錯誤!', '沒有任何的檔案可以被使用!', '請確認 getVersions () 函式內有存在的檔案可被另存!', '請程式設計者確認狀況!') : array();
             }
             try {
                 $image = ImageUtility::create($fileName = FCPATH . implode(DIRECTORY_SEPARATOR, $fileName), null);
                 $newPath = array_merge($path, array($newName = $key . $this->configs['separate_symbol'] . $name));
                 if ($this->_utility($image, FCPATH . implode(DIRECTORY_SEPARATOR, $newFileName = array_merge($this->getTempDirectory(), array($newName))), $key, $version) && S3::putObjectFile($newFileName = FCPATH . implode(DIRECTORY_SEPARATOR, $newFileName), $this->getS3Bucket(), implode(DIRECTORY_SEPARATOR, $newPath), S3::ACL_PUBLIC_READ, array(), array('Cache-Control' => 'max-age=315360000', 'Expires' => gmdate('D, d M Y H:i:s T', strtotime('+5 years')))) && @unlink($newFileName) && @unlink($fileName)) {
                     return $newPath;
                 } else {
                     return array();
                 }
             } catch (Exception $e) {
                 return $this->getDebug() ? call_user_func_array('error', $e->getMessages()) : '';
             }
             break;
     }
     return $this->getDebug() ? error('OrmImageUploader 錯誤!', '未知的 driver,系統尚未支援 ' . $this->getDriver() . ' 的空間!', '請檢查 config/system/orm_uploader.php 設定檔!') : array();
 }
Beispiel #23
0
 public function createFromOri($type, $fileName)
 {
     $uri = "{$type}/{$fileName}";
     if (($info = $this->getObjectInfo(S3Voota::getBucketOri(), $uri)) !== false) {
         $fileOnDisk = "/tmp/{$fileName}";
         if (($object = S3::getObject(S3Voota::getBucketOri(), $uri, "{$fileOnDisk}")) !== false) {
             $this->createFromFile($type, $fileOnDisk);
             unlink("{$fileOnDisk}");
         }
     }
 }
Beispiel #24
0
 /**
  * retrieve an object from a location in the current S3 bucket
  * @param string $locationOnS3 - path to the object relative to the bucket
  * @return mixed - FALSE on failure, Object array on success
  */
 public function getObject($locationOnS3, $pathToLocalFile = false)
 {
     try {
         $object = S3::getObject($this->bucket, $locationOnS3, $pathToLocalFile);
         return $object;
     } catch (Exception $e) {
         return false;
     }
 }
Beispiel #25
0
/**
 * make sure backup file is local, download it and make it local if necessary
 */
function backup_restore_locate_file($id, $path)
{
    global $amp_conf;
    $path = trim($path, '/');
    $path = str_replace(array('..', ':'), '', trim($path, '/'));
    $path = escapeshellcmd($path);
    $s = backup_get_server($id);
    if (!$s) {
        return array('error_msg' => _('Backup Server not found!'));
    }
    //dest is where we gona put backup files pulled infrom other servers
    $dest = $amp_conf['ASTSPOOLDIR'] . '/tmp/' . 'backuptmp-s' . $id . '-' . time() . '-' . basename($path);
    switch ($s['type']) {
        case 'local':
            $s['path'] = backup__($s['path']);
            $path = $s['path'] . '/' . $path;
            break;
        case 'ftp':
            //subsitute variables if nesesary
            $s['host'] = backup__($s['host']);
            $s['port'] = backup__($s['port']);
            $s['user'] = backup__($s['user']);
            $s['password'] = backup__($s['password']);
            $s['path'] = backup__($s['path']);
            $path = ltrim($path, '/');
            $connection = new Connection($s['host'], $s['user'], $s['password'], $s['port'], 90, $s['transfer'] == 'passive');
            try {
                $connection->open();
            } catch (\Exception $e) {
                $this->b['error'] = $e->getMessage();
                backup_log($this->b['error']);
                return;
            }
            $wrapper = new FTPWrapper($connection);
            $permFactory = new PermissionsFactory();
            $ftptype = $wrapper->systype();
            if (strtolower($ftptype) == "unix") {
                $fsFactory = new FilesystemFactory($permFactory);
            } else {
                $fsFactory = new WindowsFilesystemFactory();
            }
            $manager = new FTPFilesystemManager($wrapper, $fsFactory);
            $dlVoter = new DownloaderVoter();
            $dlVoter->addDefaultFTPDownloaders($wrapper);
            $ulVoter = new UploaderVoter();
            $ulVoter->addDefaultFTPUploaders($wrapper);
            $crVoter = new CreatorVoter();
            $crVoter->addDefaultFTPCreators($wrapper, $manager);
            $deVoter = new DeleterVoter();
            $deVoter->addDefaultFTPDeleters($wrapper, $manager);
            $ftp = new FTP($manager, $dlVoter, $ulVoter, $crVoter, $deVoter);
            if (!$ftp) {
                $this->b['error'] = _("Error creating the FTP object");
            }
            $ftpdirs = $ftp->findFilesystems(new \Touki\FTP\Model\Directory($s['path']));
            $file = null;
            foreach ($ftpdirs as $thisdir) {
                if ($ftp->fileExists(new \Touki\FTP\Model\File($thisdir->getRealPath() . '/' . $path))) {
                    $file = $ftp->findFileByName($thisdir->getRealPath() . '/' . $path);
                }
            }
            try {
                $options = array(FTP::NON_BLOCKING => false, FTP::TRANSFER_MODE => FTP_BINARY);
                $ftp->download($dest, $file, $options);
                $path = $dest;
            } catch (\Exception $e) {
                return array('error_msg' => _('Failed to retrieve file from server!'));
            }
            break;
        case 'ssh':
            $s['path'] = backup__($s['path']);
            $s['user'] = backup__($s['user']);
            $s['host'] = backup__($s['host']);
            $cmd[] = fpbx_which('scp');
            $cmd[] = '-o StrictHostKeyChecking=no -i';
            $cmd[] = $s['key'];
            $cmd[] = '-P ' . $s['port'];
            $cmd[] = $s['user'] . '\\@' . $s['host'] . ':' . $s['path'] . '/' . $path;
            $cmd[] = $dest;
            exec(implode(' ', $cmd), $foo, $ret);
            unset($cmd);
            if ($ret === 0) {
                $path = $dest;
            } else {
                return array('error_msg' => _('Failed to retrieve file from server!'));
            }
            break;
        case 'awss3':
            $s['bucket'] = backup__($s['bucket']);
            $s['awsaccesskey'] = backup__($s['awsaccesskey']);
            $s['awssecret'] = backup__($s['awssecret']);
            $awss3 = new S3($s['awsaccesskey'], $s['awssecret']);
            dbug('S3 Path: ' . $path);
            dbug('S3 Dest: ' . $dest);
            if ($awss3->getObject($s['bucket'], $path, $dest) !== false) {
                $path = $dest;
            } else {
                return array('error_msg' => _('Failed to retrieve file from server!'));
            }
            break;
    }
    if (file_exists($path)) {
        return $path;
    } else {
        return array('error_msg' => _('File not found! ' . $path));
    }
}
Beispiel #26
0
 function cron_process_s3_copy($s3file, $accesskey, $secretkey, $bucket, $directory)
 {
     require_once $this->_pluginPath . '/lib/s3/s3.php';
     $s3 = new S3($accesskey, $secretkey);
     $s3->getObject($bucket, $directory . $s3file, ABSPATH . 'wp-content/uploads/backupbuddy_backups/' . $s3file);
 }
<?php

$data = @S3::getObject('resources', '/sejm_komunikaty/content/' . $id . '_modified.html');
return @$data->body;
Beispiel #28
0
 function delete_from_post(&$req)
 {
     trigger_before('delete_from_post', $this, $req);
     global $db;
     if ($this->has_metadata && !isset($req->params['entry']['etag'])) {
         trigger_error("Sorry, the etag was not submitted with the database entry", E_USER_ERROR);
     }
     $fields = $this->fields_from_request($req);
     if ($this->has_metadata) {
         $atomentry = $db->models['entries']->find_by('etag', $req->params['entry']['etag']);
         $recid = $atomentry->attributes['record_id'];
     } else {
         $recid = $req->id;
     }
     $rec = $this->find($recid);
     if ($this->has_metadata) {
         $Person =& $db->model('Person');
         $Group =& $db->model('Group');
         $p = $Person->find(get_person_id());
         if (!($p->id == $atomentry->attributes['person_id']) && !$this->can_superuser($req->resource)) {
             trigger_error("Sorry, your id does not match the owner of the database entry", E_USER_ERROR);
         }
     }
     $coll = environment('collection_cache');
     if ($this->has_metadata && isset($coll[$req->resource]) && $coll[$req->resource]['location'] == 'aws') {
         $ext = extension_for($atomentry->content_type);
         $pkname = $rec->primary_key;
         global $prefix;
         $aws_file = $prefix . $rec->table . $rec->{$pkname} . "." . $ext;
         lib_include('S3');
         $s3 = new S3(environment('awsAccessKey'), environment('awsSecretKey'));
         if (!$s3) {
             trigger_error('Sorry, there was a problem connecting to Amazon Web Services', E_USER_ERROR);
         }
         if ($s3->getBucket(environment('awsBucket')) && $s3->getObject(environment('awsBucket'), urlencode($aws_file))) {
             $result = $s3->deleteObject(environment('awsBucket'), urlencode($aws_file));
             if (!$result) {
                 trigger_error('Sorry, there was a problem deleting the file from Amazon Web Services', E_USER_ERROR);
             }
         }
     }
     $result = $db->delete_record($rec);
     trigger_after('delete_from_post', $this, $req);
 }
Beispiel #29
-1
 /**
  * Read directory
  *
  * @param string $path Short path
  *
  * @return array
  */
 public function readDirectory($path)
 {
     try {
         $result = $this->client->getObject(\XLite\Core\Config::getInstance()->CDev->AmazonS3Images->bucket, $path);
     } catch (\S3Exception $e) {
         $result = array();
         \XLite\Logger::getInstance()->registerException($e);
     }
     return $result;
 }
 function getFromCloud($uri)
 {
     App::import('Vendor', 'S3', array('file' => 'S3.php'));
     $s3 = new S3($this->awsAccessKey, $this->awsSecretKey, true, "s3-ap-southeast-1.amazonaws.com");
     if (($info = $s3->getObject($this->bucketName, $uri)) !== false) {
         $path_tmp = APP . "tmp/cache/picture/";
         /*if(!is_dir($path_tmp)) {
         			mkdir(APP."tmp/cache/picture", 0777);
         		}
         		$handle = fopen($path_tmp."kossa.jpg", "w+");
         		if (fwrite($handle, $info->body) === FALSE) {
         	        echo "Cannot write to file (kossa.jpg)";
         	        exit;
         	    } else {
         		    echo "success";
         	    }*/
     }
 }