Esempio n. 1
0
 /**
  * @param RequestInterface $request
  * @param array            $options
  *
  * @return PromiseInterface
  */
 public function __invoke(RequestInterface $request, array $options)
 {
     $fn = $this->nextHandler;
     // Don't do anything if the request has no body.
     if (isset(self::$skipMethods[$request->getMethod()]) || $request->getBody()->getSize() === 0) {
         return $fn($request, $options);
     }
     $modify = [];
     // Add a default content-type if possible.
     if (!$request->hasHeader('Content-Type')) {
         if ($uri = $request->getBody()->getMetadata('uri')) {
             if ($type = Psr7\mimetype_from_filename($uri)) {
                 $modify['set_headers']['Content-Type'] = $type;
             }
         }
     }
     // Add a default content-length or transfer-encoding header.
     if (!isset(self::$skipMethods[$request->getMethod()]) && !$request->hasHeader('Content-Length') && !$request->hasHeader('Transfer-Encoding')) {
         $size = $request->getBody()->getSize();
         if ($size !== null) {
             $modify['set_headers']['Content-Length'] = $size;
         } else {
             $modify['set_headers']['Transfer-Encoding'] = 'chunked';
         }
     }
     // Add the expect header if needed.
     $this->addExpectHeader($request, $options, $modify);
     return $fn(Psr7\modify_request($request, $modify), $options);
 }
Esempio n. 2
0
 public function getPhpFileArray()
 {
     if ($this->getValue()) {
         $tmpFile = tempnam(sys_get_temp_dir(), 'crawler-uploaded-file');
         copy($this->getValue(), $tmpFile);
         return ['tmp_name' => $tmpFile, 'size' => filesize($this->getValue()), 'error' => UPLOAD_ERR_OK, 'name' => $this->getValue(), 'type' => Psr7\mimetype_from_filename($this->getValue())];
     } else {
         return ['tmp_name' => '', 'size' => '0', 'error' => UPLOAD_ERR_NO_FILE, 'name' => '', 'type' => ''];
     }
 }
 public function stream_flush()
 {
     if ($this->mode == 'r') {
         return false;
     }
     if ($this->body->isSeekable()) {
         $this->body->seek(0);
     }
     $params = $this->getOptions(true);
     $params['Body'] = $this->body;
     // Attempt to guess the ContentType of the upload based on the
     // file extension of the key
     if (!isset($params['ContentType']) && ($type = Psr7\mimetype_from_filename($params['Key']))) {
         $params['ContentType'] = $type;
     }
     return $this->boolCall(function () use($params) {
         return (bool) $this->getClient()->putObject($params);
     });
 }
Esempio n. 4
0
 public function testDetermineMimetype()
 {
     $this->assertNull(Psr7\mimetype_from_extension('not-a-real-extension'));
     $this->assertEquals('application/json', Psr7\mimetype_from_extension('json'));
     $this->assertEquals('image/jpeg', Psr7\mimetype_from_filename('/tmp/images/IMG034821.JPEG'));
 }
Esempio n. 5
0
 /**
  * @param array $args
  */
 private function resolveUploadOptions(array $args)
 {
     $args += ['bucket' => null, 'name' => null, 'validate' => true, 'resumable' => null, 'predefinedAcl' => 'private', 'metadata' => []];
     $args['data'] = Psr7\stream_for($args['data']);
     if ($args['resumable'] === null) {
         $args['resumable'] = $args['data']->getSize() > AbstractUploader::RESUMABLE_LIMIT;
     }
     if (!$args['name']) {
         $args['name'] = basename($args['data']->getMetadata('uri'));
     }
     // @todo add support for rolling hash
     if ($args['validate'] && !isset($args['metadata']['md5Hash'])) {
         $args['metadata']['md5Hash'] = base64_encode(Psr7\hash($args['data'], 'md5', true));
     }
     $args['metadata']['name'] = $args['name'];
     unset($args['name']);
     $args['contentType'] = isset($args['metadata']['contentType']) ? $args['metadata']['contentType'] : Psr7\mimetype_from_filename($args['metadata']['name']);
     $uploaderOptionKeys = ['httpOptions', 'retries', 'chunkSize', 'contentType', 'metadata'];
     $args['uploaderOptions'] = array_intersect_key($args, array_flip($uploaderOptionKeys));
     $args = array_diff_key($args, array_flip($uploaderOptionKeys));
     return $args;
 }
 protected function getInitiateParams()
 {
     $params = [];
     if (isset($this->config['acl'])) {
         $params['ACL'] = $this->config['acl'];
     }
     // Set the content type
     if ($uri = $this->source->getMetadata('uri')) {
         $params['ContentType'] = Psr7\mimetype_from_filename($uri) ?: 'application/octet-stream';
     }
     return $params;
 }
Esempio n. 7
0
 /**
  * Middleware wrapper function that adds a Content-Type header to requests.
  * This is only done when the Content-Type has not already been set, and the
  * request body's URI is available. It then checks the file extension of the
  * URI to determine the mime-type.
  *
  * @param array $operations Operations that Content-Type should be added to.
  *
  * @return callable
  */
 public static function contentType(array $operations)
 {
     return function (callable $handler) use($operations) {
         return function (CommandInterface $command, RequestInterface $request = null) use($handler, $operations) {
             if (!$request->hasHeader('Content-Type') && in_array($command->getName(), $operations, true) && ($uri = $request->getBody()->getMetadata('uri'))) {
                 $request = $request->withHeader('Content-Type', Psr7\mimetype_from_filename($uri) ?: 'application/octet-stream');
             }
             return $handler($command, $request);
         };
     };
 }
 protected function getSourceMimeType()
 {
     if ($uri = $this->source->getMetadata('uri')) {
         return Psr7\mimetype_from_filename($uri) ?: 'application/octet-stream';
     }
 }
Esempio n. 9
0
 /**
  * Composes a set of objects into a single object.
  *
  * Please note that all objects to be composed must come from the same
  * bucket.
  *
  * Example:
  * ```
  * $sourceObjects = ['log1.txt', 'log2.txt'];
  * $singleObject = $bucket->compose($sourceObjects, 'combined-logs.txt');
  * ```
  *
  * ```
  * // Use an instance of StorageObject.
  * $sourceObjects = [
  *     $bucket->object('log1.txt'),
  *     $bucket->object('log2.txt')
  * ];
  *
  * $singleObject = $bucket->compose($sourceObjects, 'combined-logs.txt');
  * ```
  *
  * @see https://cloud.google.com/storage/docs/json_api/v1/objects/compose Objects compose API documentation
  *
  * @param string[]|StorageObject[] $sourceObjects The objects to compose.
  * @param string $name The name of the composed object.
  * @param array $options [optional] {
  *     Configuration options.
  *
  *     @type string $predefinedAcl Predefined ACL to apply to the composed
  *           object. Acceptable values include, `"authenticatedRead"`,
  *           `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`,
  *           `"projectPrivate"`, and `"publicRead"`. **Defaults to**
  *           `"private"`.
  *     @type array $metadata Metadata to apply to the composed object. The
  *           available options for metadata are outlined at the
  *           [JSON API docs](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body).
  *     @type string $ifGenerationMatch Makes the operation conditional on whether the object's current generation
  *           matches the given value.
  *     @type string $ifMetagenerationMatch Makes the operation conditional on whether the object's current
  *           metageneration matches the given value.
  * }
  * @return StorageObject
  * @throws \InvalidArgumentException
  */
 public function compose(array $sourceObjects, $name, array $options = [])
 {
     if (count($sourceObjects) < 2) {
         throw new \InvalidArgumentException('Must provide at least two objects to compose.');
     }
     $options += ['destinationBucket' => $this->name(), 'destinationObject' => $name, 'destinationPredefinedAcl' => isset($options['predefinedAcl']) ? $options['predefinedAcl'] : null, 'destination' => isset($options['metadata']) ? $options['metadata'] : null, 'sourceObjects' => array_map(function ($sourceObject) {
         $name = null;
         $generation = null;
         if ($sourceObject instanceof StorageObject) {
             $name = $sourceObject->name();
             $generation = isset($sourceObject->identity()['generation']) ? $sourceObject->identity()['generation'] : null;
         }
         return array_filter(['name' => $name ?: $sourceObject, 'generation' => $generation]);
     }, $sourceObjects)];
     if (!isset($options['destination']['contentType'])) {
         $options['destination']['contentType'] = Psr7\mimetype_from_filename($name);
     }
     if ($options['destination']['contentType'] === null) {
         throw new \InvalidArgumentException('A content type could not be detected and must be provided manually.');
     }
     unset($options['metadata']);
     unset($options['predefinedAcl']);
     $response = $this->connection->composeObject(array_filter($options));
     return new StorageObject($this->connection, $response['name'], $this->identity['bucket'], $response['generation'], $response);
 }
 public function stream_flush()
 {
     if ($this->mode == 'r') {
         return false;
     }
     if ($this->body->isSeekable()) {
         $this->body->seek(0);
     }
     $params = $this->getOptions(true);
     $params['Body'] = (string) $this->body;
     // Attempt to guess the ContentType of the upload based on the
     // file extension of the key. Added by Joe Hoyle
     if (!isset($params['ContentType']) && ($type = Psr7\mimetype_from_filename($params['Key']))) {
         $params['ContentType'] = $type;
     }
     /// Expires:
     if (defined('S3_UPLOADS_HTTP_EXPIRES')) {
         $params['Expires'] = S3_UPLOADS_HTTP_EXPIRES;
     }
     // Cache-Control:
     if (defined('S3_UPLOADS_HTTP_CACHE_CONTROL')) {
         if (is_numeric(S3_UPLOADS_HTTP_CACHE_CONTROL)) {
             $params['CacheControl'] = 'max-age=' . S3_UPLOADS_HTTP_CACHE_CONTROL;
         } else {
             $params['CacheControl'] = S3_UPLOADS_HTTP_CACHE_CONTROL;
         }
     }
     /**
      * Filter the parameters passed to S3
      * Theses are the parameters passed to S3Client::putObject()
      * See; http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_putObject
      *
      * @param array $params S3Client::putObject paramteres.
      */
     $params = apply_filters('s3_uploads_putObject_params', $params);
     $this->clearCacheKey("s3://{$params['Bucket']}/{$params['Key']}");
     return $this->boolCall(function () use($params) {
         return (bool) $this->getClient()->putObject($params);
     });
 }