/** * * @param string $multipart_id * @param int $chunk The current chunk number * @param array $headers * @return array An array containing the presigned url to "PUT" the data to, the uploadId * @throws KeyNotFoundException */ public function signMultipart($multipart_id, $chunk, array $headers = array()) { if (!(list($bucket, $key) = $this->key_storage->get($multipart_id))) { throw new KeyNotFoundException('There is no upload in progress for key "' . $multipart_id . '"'); } $command = $this->s3->getCommand('UploadPart', array('Bucket' => $bucket, 'Key' => $key, 'UploadId' => $multipart_id, 'Body' => '', 'PartNumber' => (string) $chunk + 1, 'command.headers' => $headers)); return array('url' => $command->createPresignedUrl('+10 minutes'), 'uploadId' => $multipart_id); }
public function testBasicOperations() { $inputBucket = 'php-integ-transcoder-test-bucket-input'; $outputBucket = 'php-integ-transcoder-test-bucket-output'; $roleName = 'php-integ-transcoder-test-role'; $policyName = 'php-integ-transcoder-test-policy'; $pipelineName = 'php-integ-transcoder-test-pipeline'; self::log('Create input and output buckets for the Elastic Transcoder pipeline.'); $commands = array(); $commands[] = $this->s3->getCommand('CreateBucket', array('Bucket' => $inputBucket)); $commands[] = $this->s3->getCommand('CreateBucket', array('Bucket' => $outputBucket)); $this->s3->execute($commands); self::log('Create an IAM Role for the Elastic Transcoder pipeline.'); $result = $this->iam->getCommand('CreateRole', array('RoleName' => $roleName, 'AssumeRolePolicyDocument' => self::DUMMY_IAM_POLICY_ASSUME_ROLE))->getResult(); $roleArn = $result->getPath('Role/Arn'); self::log('Put a policy on the IAM Role for the Elastic Transcoder pipeline.'); $result = $this->iam->getCommand('PutRolePolicy', array('PolicyName' => $policyName, 'RoleName' => $roleName, 'PolicyDocument' => self::DUMMY_IAM_POLICY_ALLOW_S3))->getResult(); self::log('Use TestRole to validate our pipeline inputs. NOTE: Ours are not valid on purpose.'); $result = $this->transcoder->getCommand('TestRole', array('InputBucket' => $inputBucket, 'OutputBucket' => $outputBucket, 'Role' => $roleArn, 'Topics' => array()))->getResult(); $this->assertEquals('false', $result['Success']); self::log('Create an Elastic Transcoder pipeline.'); $result = $this->transcoder->getCommand('CreatePipeline', array('Name' => $pipelineName, 'InputBucket' => $inputBucket, 'OutputBucket' => $outputBucket, 'Role' => $roleArn, 'Notifications' => array_fill_keys(array('Progressing', 'Completed', 'Warning', 'Error'), '')))->getResult(); $pipelineId = $result->getPath('Pipeline/Id'); self::log('Make sure created Elastic Transcoder pipeline is in the list of pipelines.'); $result = $this->transcoder->getCommand('ListPipelines')->getResult(); $pipelineNames = $result->getPath('Pipelines/*/Name'); $this->assertContains($pipelineName, $pipelineNames); self::log('Make sure ListPipelines iterator works.'); $found = false; foreach ($this->transcoder->getIterator('ListPipelines') as $pipeline) { if ($pipeline['Name'] == $pipelineName) { $found = true; break; } } if (!$found) { $this->fail('Did not find the pipeline in the iterator results.'); } self::log('Make sure created Elastic Transcoder pipeline can be read.'); $result = $this->transcoder->getCommand('ReadPipeline', array('Id' => $pipelineId))->getResult(); $this->assertEquals($pipelineName, $result->getPath('Pipeline/Name')); self::log('Delete the Elastic Transcoder pipeline.'); $response = $this->transcoder->getCommand('DeletePipeline', array('Id' => $pipelineId))->getResponse(); $this->assertEquals(202, $response->getStatusCode()); self::log('Delete the policy from the IAM Role for the Elastic Transcoder pipeline.'); $result = $this->iam->getCommand('DeleteRolePolicy', array('PolicyName' => $policyName, 'RoleName' => $roleName))->getResult(); self::log('Delete the IAM Role for the Elastic Transcoder pipeline.'); $result = $this->iam->getCommand('DeleteRole', array('RoleName' => $roleName))->getResult(); self::log('Delete the input and output buckets for the Elastic Transcoder pipeline.'); $commands = array(); $commands[] = $this->s3->getCommand('DeleteBucket', array('Bucket' => $inputBucket)); $commands[] = $this->s3->getCommand('DeleteBucket', array('Bucket' => $outputBucket)); $this->s3->execute($commands); }
/** * Create a link to a S3 object from a bucket. If expiration is not empty, then it is used to create * a signed URL * * @param string $object The object name (full path) * @param string $bucket The bucket name * @param string|int $expiration The Unix timestamp to expire at or a string that can be evaluated by strtotime * @throws InvalidDomainNameException * @return string */ public function __invoke($object, $bucket = '', $expiration = '') { $bucket = trim($bucket ?: $this->getDefaultBucket(), '/'); if (empty($bucket)) { throw new InvalidDomainNameException('An empty bucket name was given'); } if ($expiration) { $command = $this->client->getCommand('GetObject', ['Bucket' => $bucket, 'Key' => $object]); return $this->client->createPresignedRequest($command, $expiration)->getUri()->__toString(); } else { return $this->client->getObjectUrl($bucket, $object); } }
/** * @depends testPutAndListObjects */ public function testPutBucketTagging() { self::log("Adding tags to a bucket"); $command = $this->client->getCommand('PutBucketTagging', array('Bucket' => $this->bucket, 'TagSet' => array(array('Key' => 'Foo', 'Value' => 'Bar'), array('Key' => 'Baz', 'Value' => 'Boo')))); $command->execute(); $this->assertNull($command->getRequest()->getHeader('Expect')); }
/** * {@inheritDoc} */ public function listObjectsAsync(AwsS3Request $request) { /* Create the command. */ $command = $this->client->getCommand(self::COMMAND_TYPE_LIST_OBJECTS, $request->toArray()); /* Execute the command. */ return $this->executeAsyncCommand($command); }
/** * Get a URL to the resource. * * @param \CipeMotion\Medialibrary\Entities\File $file * @param \CipeMotion\Medialibrary\Entities\Transformation|null $tranformation * @param bool $fullPreview * @param bool $download * * @return string */ public function getUrlForTransformation(File $file, Transformation $tranformation = null, $fullPreview = false, $download = false) { if (empty($tranformation)) { $tranformationName = 'upload'; $extension = $file->extension; if ($fullPreview && $file->type !== FileTypes::TYPE_IMAGE) { $tranformationName = 'preview'; $extension = 'jpg'; } } else { $tranformationName = $tranformation->name; $extension = $tranformation->extension; } $commandParams = ['ResponseCacheControl' => 'private, max-age=1200', 'ResponseContentType' => $file->mime_type, 'Bucket' => array_get($this->config, 'bucket'), 'Key' => "{$file->id}/{$tranformationName}.{$extension}"]; if ($download) { $commandParams['ResponseContentDisposition'] = "attachment; filename={$file->filename}"; } $expires = array_get($this->config, 'presigned.expires', '+20 minutes'); $command = $this->client->getCommand('GetObject', $commandParams); return (string) $this->client->createPresignedRequest($command, $expires)->getUri(); }
/** * Get the object acl presented as a visibility. * * @param string $path * * @return string */ protected function getRawVisibility($path) { $command = $this->s3Client->getCommand('getObjectAcl', ['Bucket' => $this->bucket, 'Key' => $this->applyPathPrefix($path)]); $result = $this->s3Client->execute($command); $visibility = AdapterInterface::VISIBILITY_PRIVATE; foreach ($result->get('Grants') as $grant) { if (isset($grant['Grantee']['URI']) && $grant['Grantee']['URI'] === self::PUBLIC_GRANT_URI && $grant['Permission'] === 'READ') { $visibility = AdapterInterface::VISIBILITY_PUBLIC; break; } } return $visibility; }
/** * {@inheritdoc} */ public function fetch($id) { try { $this->initClient(); $command = $this->client->getCommand('GetObject', array('Bucket' => $this->bucketName, 'Key' => $this->objectKey)); $result = $command->execute(); } catch (AwsExceptionInterface $e) { throw new RuntimeException('An AmazonWebService exception occured', $e->getCode(), $e); } catch (\Exception $e) { throw new RuntimeException('An unexpected error occured', $e->getCode(), $e); } return $result['Body']; }
/** * @param $location * * @return bool */ protected function doesDirectoryExist($location) { // Maybe this isn't an actual key, but a prefix. // Do a prefix listing of objects to determine. $command = $this->s3Client->getCommand('listObjects', ['Bucket' => $this->bucket, 'Prefix' => rtrim($location, '/') . '/', 'MaxKeys' => 1]); try { $result = $this->s3Client->execute($command); return $result['Contents'] || $result['CommonPrefixes']; } catch (S3Exception $e) { if ($e->getStatusCode() === 403) { return false; } throw $e; } }
/** * @depends testPutAndListObjects * @dataProvider prefixKeyProvider */ public function testWorksWithPrefixKeys($key, $cleaned, $encoded) { $this->client->waitUntil('bucket_exists', array('Bucket' => $this->bucket)); $command = $this->client->getCommand('PutObject', array('Bucket' => $this->bucket, 'Key' => $key, 'SourceFile' => __FILE__)); $command->execute(); // Ensure the path is correct $this->assertEquals($encoded, $command->getRequest()->getPath()); // Ensure the key is not an array and is returned to it's previous value $this->assertEquals($key, $command['Key']); $this->client->waitUntil('object_exists', array('Bucket' => $this->bucket, 'Key' => $key)); $result = $this->client->getObject(array('Bucket' => $this->bucket, 'Key' => $key)); $this->assertEquals(file_get_contents(__FILE__), (string) $result['Body']); // Test using path style hosting $command = $this->client->getCommand('DeleteObject', array('Bucket' => $this->bucket, 'Key' => $key, 'PathStyle' => true)); $command->execute(); $this->assertEquals('/' . $this->bucket . $encoded, $command->getRequest()->getPath()); }
public function getPreSignedUrl($bucket, $key, $expiryInMinutes = 10) { $this->bucket = $bucket; $this->key = $key; $this->scenario = 'delete'; if ($this->validate()) { try { $s3Client = new S3Client(['version' => 'latest', 'region' => Yii::$app->params['amazon']['region'], 'credentials' => Yii::$app->params['amazon']['credentials']]); $cmd = $s3Client->getCommand('GetObject', ['Bucket' => $this->bucket, 'Key' => $this->key]); $request = $s3Client->createPresignedRequest($cmd, '+' . $expiryInMinutes . ' minutes'); return (string) $request->getUri(); } catch (\Exception $e) { Yii::error('Error getting pre-signed url from S3. Bucket - ' . $this->bucket . ' Key - ' . $this->key . ' Extra - ' . $e->getMessage()); return false; } } return false; }
/** * @depends testPutAndListObjects */ public function testPreSignedUrlAllowsSpecialCharacters() { self::log('Uploading an object with a space in the key'); $this->client->waitUntil('bucket_exists', array('Bucket' => $this->bucket)); $key = 'foo baz bar!'; $this->client->putObject(array('Bucket' => $this->bucket, 'Key' => $key, 'Body' => 'hi')); $this->client->waitUntil('object_exists', array('Bucket' => $this->bucket, 'Key' => $key)); self::log('Creating an downloading using a pre-signed URL with command'); $command = $this->client->getCommand('GetObject', array('Bucket' => $this->bucket, 'Key' => $key)); $url = $command->createPresignedUrl('+100 minutes'); self::log($url); $this->assertEquals('hi', file_get_contents($url)); self::log('Creating an downloading using a pre-signed URL'); $extra = urlencode("attachment; filename=\"{$key}\""); $request = $this->client->get("{$this->bucket}/{$key}?response-content-disposition={$extra}"); $url = $this->client->createPresignedUrl($request, '+10 minutes'); self::log($url); $client = new Client(); $this->assertEquals('hi', file_get_contents($url)); $this->assertEquals('hi', $client->get($url)->send()->getBody(true)); }
/** * @param string $name * @param string $data * @return mixed */ public function saveFile($name, $data) { $command = $this->client->getCommand('PutObject', ['Bucket' => $this->getBucket(), 'Key' => $name, 'Body' => $data, 'ACL' => 'public-read']); return $this->client->execute($command); }
// Display files currently uploaded in S3Bucket $o_iter = $s3client->getIterator('ListObjects', array('Bucket' => $s3Bucket)); foreach ($o_iter as $o) { if ($o['Size'] != '0') { // Because we don't want to list folders echo "<form enctype='multipart/form-data' name='fileDELForm' method='post' action='index.php' style='border:1px;' >"; $prefixKey = explode("/", $o['Key']); if ($prefixKey[0] == 'public') { echo "<a href='http://" . $s3Bucket . "/" . $o['Key'] . "'>"; echo "<img src='http://{$s3Bucket}/" . $o['Key'] . "' style='width:100px;height:100px;'/></a>"; echo "<input type='hidden' name='fileKey' id='fileKey' value='" . $o['Key'] . "' />"; echo "{$o['Key']}"; echo "<input type='submit' name='submit' id='submit' value='Delete' />"; } if ($prefixKey[0] == 'QSA') { $objectPre = $s3client->getCommand('GetObject', ['Bucket' => $s3Bucket, 'Key' => $o['Key']]); $presignedRequest = $s3client->createPresignedRequest($objectPre, '+30 minutes'); $objectURL = (string) $presignedRequest->getUri(); echo "<a href='{$objectURL}' >"; echo "<img src='{$objectURL}' style='width:100px;height:100px;' /></a>"; echo "<input type='hidden' name='fileKey' id='fileKey' value='" . $o['Key'] . "' />"; echo "{$o['Key']}"; echo "<input type='submit' name='submit' id='submit' value='Delete' />"; } echo "</form>"; } } // Check if the UL form has been posted if ($submit == 'Upload') { if (isset($s3Bucket) && is_uploaded_file($_FILES['fileUL']['tmp_name'])) { $finfo = finfo_open(FILEINFO_MIME_TYPE);