Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace BackEnd\Services;
- define('PROJECT_ROOT', realpath(__DIR__ . '/..'));
- require PROJECT_ROOT . '/../../vendor/autoload.php';
- use Aws\S3\S3Client;
- use Aws\Exception\AwsException;
- use Aws\S3\Exception\S3Exception;
- use Aws\Sts\StsClient;
- class AWSS3
- {
- // ACL flags
- const ACL_PRIVATE = 'private';
- const ACL_PUBLIC_READ = 'public-read';
- const ACL_PUBLIC_READ_WRITE = 'public-read-write';
- const ACL_AUTHENTICATED_READ = 'authenticated-read';
- const STORAGE_CLASS_STANDARD = 'STANDARD';
- const STORAGE_CLASS_RRS = 'REDUCED_REDUNDANCY';
- const STORAGE_CLASS_STANDARD_IA = 'STANDARD_IA';
- const SSE_NONE = '';
- const SSE_AES256 = 'AES256';
- /**
- * The AWS Access key
- *
- * @var string
- * @access private
- * @static
- */
- private static $__accessKey = null;
- /**
- * AWS Secret Key
- *
- * @var string
- * @access private
- * @static
- */
- private static $__secretKey = null;
- /**
- * SSL Client key
- *
- * @var string
- * @access private
- * @static
- */
- private static $__sslKey = null;
- /**
- * Default delimiter to be used, for example while getBucket().
- * @var string
- * @access public
- * @static
- */
- public static $defDelimiter = null;
- /**
- * AWS URI
- *
- * @var string
- * @acess public
- * @static
- */
- public static $endpoint = 's3.amazonaws.com';
- /**
- * Proxy information
- *
- * @var null|array
- * @access public
- * @static
- */
- public static $proxy = null;
- /**
- * Connect using SSL?
- *
- * @var bool
- * @access public
- * @static
- */
- public static $useSSL = false;
- /**
- * Use SSL validation?
- *
- * @var bool
- * @access public
- * @static
- */
- public static $useSSLValidation = true;
- /**
- * Use SSL version
- *
- * @var const
- * @access public
- * @static
- */
- public static $useSSLVersion = CURL_SSLVERSION_TLSv1;
- /**
- * Use PHP exceptions?
- *
- * @var bool
- * @access public
- * @static
- */
- public static $useExceptions = false;
- /**
- * Time offset applied to time()
- * @access private
- * @static
- */
- private static $__timeOffset = 0;
- /**
- * SSL client key
- *
- * @var bool
- * @access public
- * @static
- */
- public static $sslKey = null;
- /**
- * SSL client certfificate
- *
- * @var string
- * @acess public
- * @static
- */
- public static $sslCert = null;
- /**
- * SSL CA cert (only required if you are having problems with your system CA cert)
- *
- * @var string
- * @access public
- * @static
- */
- public static $sslCACert = null;
- /**
- * Bucketname
- *
- * @var string
- * @access public
- * @static
- */
- public static $bucketname = '';
- /**
- * Basepath
- *
- * @var string
- * @access public
- * @static
- */
- public static $basepath = '';
- /**
- * AWS Key Pair ID
- *
- * @var string
- * @access private
- * @static
- */
- private static $__signingKeyPairId = null;
- /**
- * Key resource, freeSigningKey() must be called to clear it from memory
- *
- * @var bool
- * @access private
- * @static
- */
- private static $__signingKeyResource = false;
- private static $__client = null;
- private static $__stsclient = null;
- private static $__sessionname = 'sessionname';
- private static $__profile = 'arn:aws:iam::ID:instance-profile/POD-ROLE';
- public static $region = null;
- /**
- * 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 $endpoint Amazon URI
- * @return void
- */
- public function __construct($accessKey = null, $secretKey = null, $useSSL = false, $endpoint = null, $bucketname = null, $basepath = null, $region = 'eu-west-1')
- {
- if (($accessKey !== null && $accessKey !== "") && ($secretKey !== null && $secretKey !== "")) {
- self::setAuth($accessKey, $secretKey);
- self::$__accessKey = $accessKey;
- self::$__secretKey = $secretKey;
- }
- self::$useSSL = $useSSL;
- self::$endpoint = $endpoint;
- if ($basepath !== null)
- self::setBasepath($basepath);
- if ($bucketname !== null)
- self::setBucketname($bucketname);
- if ($region !== null)
- self::setRegion($region);
- $this->setClient();
- }
- public function getRegion()
- {
- return self::$region;
- }
- public function getBasepath()
- {
- return self::$basepath;
- }
- public function getBucketname()
- {
- return self::$bucketname;
- }
- public function getEndpoint()
- {
- return self::$endpoint;
- }
- public static function setBucketname($name)
- {
- self::$bucketname = $name;
- }
- public static function setBasepath($base)
- {
- self::$basepath = $base;
- }
- public function setClient()
- {
- //Se sono in possesso delle credenziali mi autentico, altrimenti uso il ruolo associato all'utenza
- try {
- if (self::hasAuth()) {
- self::$__client = new S3Client([
- 'version' => 'latest',
- 'region' => $this->getRegion(),
- 'credentials' => [
- 'key' => self::$__accessKey,
- 'secret' => self::$__secretKey,
- ],
- ]);
- } else {
- self::$__stsclient = new StsClient(
- [
- 'profile' => self::$__profile,
- 'version' => 'latest',
- 'region' => $this->getRegion(),
- 'use_aws_shared_config_files' => false,
- 'debug' => true
- ]
- );
- // print_r(self::$__stsclient);
- $result = self::$__stsclient->AssumeRole([
- 'RoleArn' => 'arn:aws:iam::ID:role/POD-ROLE',
- 'RoleSessionName' => self::$__sessionname,
- ]);
- echo "RESULT START";
- print_r($result);
- echo "RESULT END";
- self::$__client = new S3Client([
- 'version' => 'latest',
- 'region' => $this->getRegion(),
- 'debug' => true,
- 'credentials' => [
- 'key' => $result['Credentials']['AccessKeyId'],
- 'secret' => $result['Credentials']['SecretAccessKey'],
- 'token' => $result['Credentials']['SessionToken']
- ]
- ]);
- echo "CLIENT START";
- print_r(self::$__client);
- echo "CLIENT END";
- }
- } catch (AwsException $e) {
- echo $e->getMessage();
- echo "\n";
- }
- }
- public static function setRegion($region)
- {
- self::$region = $region;
- }
- /**
- * Set the service endpoint
- *
- * @param string $host Hostname
- * @return void
- */
- public function setEndpoint($host)
- {
- self::$endpoint = $host;
- }
- /**
- * Set AWS access key and secret key
- *
- * @param string $accessKey Access key
- * @param string $secretKey Secret key
- * @return void
- */
- public static function setAuth($accessKey, $secretKey)
- {
- self::$__accessKey = $accessKey;
- self::$__secretKey = $secretKey;
- }
- /**
- * Check if AWS keys have been set
- *
- * @return boolean
- */
- public static function hasAuth()
- {
- return (self::$__accessKey !== null && self::$__secretKey !== null);
- }
- /**
- * Set SSL on or off
- *
- * @param boolean $enabled SSL enabled
- * @param boolean $validate SSL certificate validation
- * @return void
- */
- public static function setSSL($enabled, $validate = true)
- {
- self::$useSSL = $enabled;
- self::$useSSLValidation = $validate;
- }
- /**
- * Set SSL client certificates (experimental)
- *
- * @param string $sslCert SSL client certificate
- * @param string $sslKey SSL client key
- * @param string $sslCACert SSL CA cert (only required if you are having problems with your system CA cert)
- * @return void
- */
- public static function setSSLAuth($sslCert = null, $sslKey = null, $sslCACert = null)
- {
- self::$sslCert = $sslCert;
- self::$sslKey = $sslKey;
- self::$sslCACert = $sslCACert;
- }
- /**
- * Set proxy information
- *
- * @param string $host Proxy hostname and port (localhost:1234)
- * @param string $user Proxy username
- * @param string $pass Proxy password
- * @param constant $type CURL proxy type
- * @return void
- */
- public static function setProxy($host, $user = null, $pass = null, $type = CURLPROXY_SOCKS5)
- {
- self::$proxy = array('host' => $host, 'type' => $type, 'user' => $user, 'pass' => $pass);
- }
- public static function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE)
- {
- if (self::$__client == null) return false;
- try {
- $result = self::$__client->putObject(['Bucket' => $bucket, 'Key' => $uri, 'Body' => file_get_contents($file), 'ACL' => $acl]);
- return $result['ObjectURL'];
- } catch (S3Exception $e) {
- echo "There was an error uploading the file.\n";
- echo $e->getMessage() . "\n";
- echo $e->getTraceAsString();
- return false;
- }
- }
- public static function deleteObject($bucketName, $bucketfile)
- {
- if (self::$__client == null) return false;
- try {
- self::$__client->deleteObject(['Bucket' => $bucketName, 'Key' => $bucketfile]);
- return true;
- } catch (S3Exception $e) {
- echo "There was an error deleting the file.\n";
- echo $e->getMessage() . "\n";
- echo $e->getTraceAsString();
- return false;
- }
- }
- public static function getBucket($bucketname, $path)
- {
- $objects = self::$__client->getIterator('ListObjects', array(
- 'Bucket' => $bucketname,
- 'Prefix' => $path . (substr($path, -1) == '/' ? '' : '/')
- ));
- return $objects;
- }
- public static function getListObjects($bucketName, $bucketfile)
- {
- if (self::$__client == null) return false;
- $objects = [];
- try {
- $results = self::$__client->getPaginator('ListObjects', ['Bucket' => $bucketName, 'Prefix' => $bucketfile]);
- foreach ($results as $result) {
- if ($result['Contents'] !== null) {
- foreach ($result['Contents'] as $object) {
- if ($object['Size'] > 0) {
- $object['url'] = strpos($bucketfile, 'public') ? self::getObjectUrl($bucketName, $object['Key']) : self::getSignedUrl($bucketName, $object['Key']);
- array_push($objects, $object);
- }
- }
- }
- }
- return $objects;
- } catch (S3Exception $e) {
- echo "There was an error getting list of files.\n";
- echo $e->getMessage() . "\n";
- echo $e->getTraceAsString();
- return false;
- }
- }
- public static function getSignedUrl($bucketName, $bucketfile)
- {
- if (self::$__client == null) return false;
- try {
- $cmd = self::$__client->getCommand('GetObject', ['Bucket' => $bucketName, 'Key' => $bucketfile]);
- $request = self::$__client->createPresignedRequest($cmd, '+60minutes');
- $url = (string)$request->getUri();
- return $url;
- } catch (S3Exception $e) {
- echo "There was an error getting the signataure of files.\n";
- echo $e->getMessage() . "\n";
- echo $e->getTraceAsString();
- return false;
- }
- }
- public static function getObjectUrl($bucketName, $bucketfile)
- {
- if (self::$__client == null) return false;
- try {
- $url = self::$__client->getObjectUrl($bucketName,$bucketfile);
- return $url;
- } catch (S3Exception $e) {
- echo "There was an error getting the object url of file.\n";
- echo $e->getMessage() . "\n";
- echo $e->getTraceAsString();
- return false;
- }
- }
- public static function getSingleObject($bucketName, $bucketfile)
- {
- if (self::$__client == null) return false;
- $objects = [];
- try {
- $results = self::$__client->getPaginator('ListObjects', ['Bucket' => $bucketName, 'Prefix' => $bucketfile]);
- foreach ($results as $result) {
- if ($result['Contents'] !== null) {
- if ($result['Contents'] !== null) {
- if ($result['Contents'][0] !== null) {
- $object = $result['Contents'][0];
- $object['url'] = strpos($bucketfile, 'public') ? self::getObjectUrl($bucketName, $object['Key']) : self::getSignedUrl($bucketName, $object['Key']);
- return $object['url'];
- }
- }
- }
- }
- return $objects;
- } catch (S3Exception $e) {
- echo "There was an error getting list of files.\n";
- echo $e->getMessage() . "\n";
- echo $e->getTraceAsString();
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment