예제 #1
0
 /**
  * Uploads a file to storage and returns the url of the new file.
  *
  * @param $localFilePath string
  * @param $contentType string
  *
  * @return string A URL pointing to the stored file.
  */
 public function storeFile($localFilePath, $contentType)
 {
     $obj = new \Google_Service_Storage_StorageObject();
     // Generate a unique file name so we don't try to write to files to
     // the same name.
     $name = uniqid('', true);
     $obj->setName($name);
     $obj = $this->service->objects->insert($this->bucketName, $obj, array('data' => file_get_contents($localFilePath), 'uploadType' => 'media', 'name' => $name, 'predefinedAcl' => 'publicread'));
     return $obj->getMediaLink();
 }
 public function media_file_upload($_bucket = null, $_file = null, $_name = null)
 {
     # init
     $result = new stdClass();
     $result->error = null;
     $result->status = null;
     $result->exception = null;
     # timer
     $result->starttime = microtime();
     # init gcs api
     $gso = new Google_Service_Storage_StorageObject();
     $gso->setName($_name);
     $gso->setBucket($_bucket);
     $finfo = finfo_open(FILEINFO_MIME_TYPE);
     $mimetype = finfo_file($finfo, $_file);
     $chunkSizeBytes = 1 * 1024 * 1024;
     $this->client->setDefer(true);
     $filetoupload = array('name' => $_name, 'uploadType' => 'resumable');
     # service
     $this->newStorageService();
     $status = false;
     # try
     try {
         $request = $this->storageService->objects->insert($_bucket, $gso, $filetoupload);
         $media = new Google_Http_MediaFileUpload($this->client, $request, $mimetype, null, true, $chunkSizeBytes);
         $media->setFileSize(filesize($_file));
         $handle = fopen($_file, "rb");
         # loop chunks
         while (!$status && !feof($handle)) {
             $chunk = fread($handle, $chunkSizeBytes);
             $status = $media->nextChunk($chunk);
         }
         fclose($handle);
         $this->client->setDefer(false);
         $result->status = $status;
     } catch (Exception $e) {
         $result->error = true;
         $result->status = 'GCS upload failed';
         $result->exception = $e;
     }
     # timer
     $result->endtime = microtime();
     $result->totaltime = $this->get_totaltime($result);
     # verify response
     $result->httpcode = http_response_code();
     $result->error = isset($status->kind) && $status->kind == self::STORAGE_OBJECT ? false : true;
     return $result;
 }
예제 #3
0
function storeGCS(&$content, $bucket, $file)
{
    $client = getClient();
    $storage = getStorageService($client);
    try {
        $body = array('name' => $file, 'data' => $content, 'uploadType' => "media");
        $gsso = new Google_Service_Storage_StorageObject();
        $gsso->setName($file);
        $result = $storage->objects->insert($bucket, $gsso, $body);
        //print_r($result);  // prints on browser console (or javascript, ajax)
    } catch (Exception $e) {
        syslog(LOG_EMERG, $e->getMessage());
        print $e->getMessage();
        sendMail('Cannot store data in GCS: ' . $e->getMessage());
        return 1;
    }
    return 0;
}
 public function uploadFile($file)
 {
     $storageService = new \Google_Service_Storage($this->client);
     $mimeType = $file->getMimetype();
     $fileExtension = $file->getClientOriginalExtension();
     $datePrefix = '-' . Carbon::now()->toDateString() . '_' . Carbon::now()->toTimeString();
     $file_name = explode('.', $file->getClientOriginalName())[0];
     $file_name = $file_name . $datePrefix . '.' . $fileExtension;
     /***
      * Write file to Google Storage
      */
     try {
         $postbody = array('name' => $file_name, 'data' => file_get_contents($file->getPathname()), 'uploadType' => "media", 'mimeType' => $mimeType);
         $gsso = new \Google_Service_Storage_StorageObject();
         $gsso->setName($file_name);
         $result = $storageService->objects->insert($this->projectBucket, $gsso, $postbody);
         return $result;
     } catch (\Exception $e) {
         echo $e->getMessage();
     }
 }
예제 #5
0
 /**
  * {@inheritdoc}
  */
 public function write($key, $content)
 {
     $this->ensureBucketExists();
     $path = $this->computePath($key);
     $metadata = $this->getMetadata($key);
     $options = array('uploadType' => 'multipart', 'data' => $content);
     /**
      * If the ContentType was not already set in the metadata, then we autodetect
      * it to prevent everything being served up as application/octet-stream.
      */
     if (!isset($metadata['ContentType']) && $this->detectContentType) {
         $finfo = new \finfo(FILEINFO_MIME_TYPE);
         $options['mimeType'] = $finfo->buffer($content);
         unset($metadata['ContentType']);
     } elseif (isset($metadata['ContentType'])) {
         $options['mimeType'] = $metadata['ContentType'];
         unset($metadata['ContentType']);
     }
     $object = new \Google_Service_Storage_StorageObject();
     $object->name = $path;
     if (isset($metadata['ContentDisposition'])) {
         $object->setContentDisposition($metadata['ContentDisposition']);
         unset($metadata['ContentDisposition']);
     }
     if (isset($metadata['CacheControl'])) {
         $object->setCacheControl($metadata['CacheControl']);
         unset($metadata['CacheControl']);
     }
     if (isset($metadata['ContentLanguage'])) {
         $object->setContentLanguage($metadata['ContentLanguage']);
         unset($metadata['ContentLanguage']);
     }
     if (isset($metadata['ContentEncoding'])) {
         $object->setContentEncoding($metadata['ContentEncoding']);
         unset($metadata['ContentEncoding']);
     }
     $object->setMetadata($metadata);
     try {
         $object = $this->service->objects->insert($this->bucket, $object, $options);
         if ($this->options['acl'] == 'public') {
             $acl = new \Google_Service_Storage_ObjectAccessControl();
             $acl->setEntity("allUsers");
             $acl->setRole("READER");
             $this->service->objectAccessControls->insert($this->bucket, $path, $acl);
         }
         return $object->getSize();
     } catch (\Google_Service_Exception $e) {
         return false;
     }
 }
예제 #6
0
 public function credentials_test_engine()
 {
     $this->options = $this->get_opts();
     $opts = $this->options;
     if (empty($opts['token']) || empty($_POST['clientid']) || empty($_POST['secret']) || $_POST['clientid'] != $opts['clientid'] || $_POST['secret'] != $opts['secret']) {
         _e("You must save and authenticate before you can test your settings.", 'updraftplus');
         return;
     }
     $ssl_useservercerts = (bool) $_POST['useservercerts'];
     $ssl_disableverify = (bool) $_POST['disableverify'];
     // Not currently used: we always do SSL.
     // Without SSL is possible: https://cloud.google.com/storage/docs/reference-uris?hl=en
     // 		$nossl = $_POST['nossl'];
     $opts['ssl_useservercerts'] = $ssl_useservercerts;
     $opts['ssl_disableverify'] = $ssl_disableverify;
     $service = $this->bootstrap($opts);
     if (is_wp_error($service)) {
         echo __("Failed", 'updraftplus') . ". ";
         foreach ($service->get_error_messages() as $key => $msg) {
             echo "{$msg}\n";
         }
         die;
     }
     $storage_class = !empty($_POST['storage_class']) && isset($this->storage_classes[$_POST['storage_class']]) ? $_POST['storage_class'] : 'STANDARD';
     $bucket_location = !empty($_POST['bucket_location']) && isset($this->bucket_locations[$_POST['bucket_location']]) ? $_POST['bucket_location'] : 'US';
     $opts['bucket_location'] = $bucket_location;
     $opts['storage_class'] = $storage_class;
     list($bucket_name, $path) = $this->split_bucket_path($_POST['bucket_path']);
     if (empty($bucket_name)) {
         _e("Failure: No bucket details were given.", 'updraftplus');
         return;
     }
     // Project ID only needed if creating a bucket
     if (isset($_POST['project_id'])) {
         $project_id = (string) $_POST['project_id'];
         $opts['project_id'] = $project_id;
     }
     // Save them so that create_bucket_if_not_existing uses them instead of the saved ones
     $this->options = $opts;
     $this->service = $service;
     $bucket = $this->create_bucket_if_not_existing($bucket_name, $storage_class, $bucket_location);
     if (is_wp_error($bucket)) {
         echo __("Failed", 'updraftplus') . ". ";
         foreach ($bucket->get_error_messages() as $key => $msg) {
             echo "{$msg}\n";
         }
         die;
     } elseif (!is_a($bucket, 'Google_Service_Storage_Bucket')) {
         echo __("Failed", 'updraftplus') . ". (" . serialize($bucket) . ")";
         die;
     }
     $random_file_name = md5(rand()) . '.tmp';
     $storage_object = new Google_Service_Storage_StorageObject();
     $storage_object->setName($random_file_name);
     $storage_object->setBucket($bucket_name);
     try {
         $result = $service->objects->insert($bucket_name, $storage_object, array('data' => 'UpdraftPlus connection test temporary file - you can delete this', 'mimeType' => 'text/plain', 'uploadType' => 'media'));
     } catch (Exception $e) {
         echo __('Failure', 'updraftplus') . ": " . __('We successfully accessed the bucket, but the attempt to create a file in it failed.', 'updraftplus') . "\n";
         echo $e->getMessage();
         die;
     }
     if (is_a($result, 'Google_Service_Storage_StorageObject')) {
         echo __('Success', 'updraftplus') . ": " . __('We accessed the bucket, and were able to create files within it.', 'updraftplus') . "\n";
         try {
             $delete_result = $service->objects->delete($bucket_name, $random_file_name);
         } catch (Exception $e) {
             echo ' ' . __('Delete failed:', 'updraftplus') . ' ' . $e->getMessage();
         }
         die;
     } else {
         echo __('Failure', 'updraftplus') . ": " . __('We successfully accessed the bucket, but the attempt to create a file in it failed.', 'updraftplus') . ' (' . get_class($result) . ')';
     }
     die;
 }
 protected function InsertFile()
 {
     $postBody = new Google_Service_Storage_StorageObject();
     $postBody->setName($this->path);
     if (isset($this->filecontext['Content-Type'])) {
         $content_type = $this->filecontext['Content-Type'];
     } else {
         $content_type = $this->detectMimetype($this->path);
     }
     return static::$service->objects->insert($this->bucket, $postBody, array('data' => $this->fileBody, 'mimeType' => $content_type, 'uploadType' => 'resumable'));
 }
 /**
  * {@inheritdoc}
  */
 public function setVisibility($path, $visibility)
 {
     $object = new \Google_Service_Storage_StorageObject();
     $object->setAcl([]);
     $params = ['predefinedAcl' => $visibility == AdapterInterface::VISIBILITY_PUBLIC ? 'publicRead' : 'private'];
     $this->service->objects->patch($this->bucket, $path, $object, $params);
     return compact('path', 'visibility');
 }
예제 #9
0
if (isset($_FILES['image'])) {
    $errors = array();
    $file_name = $_FILES['image']['name'];
    $file_size = $_FILES['image']['size'];
    $file_tmp = $_FILES['image']['tmp_name'];
    $file_type = $_FILES['image']['type'];
    $file_ext = strtolower(end(explode('.', $_FILES['image']['name'])));
    $extensions = array("jpeg", "jpg", "png");
    if (in_array($file_ext, $extensions) === false) {
        $errors[] = "extension not allowed, please choose a JPEG or PNG file. \r\n";
    }
    if ($file_size > 2097152) {
        $errors[] = 'File size must be under 2 MB \\r\\n';
    }
    if (empty($errors) == true) {
        $obj = new Google_Service_Storage_StorageObject();
        $obj->setName($folder . $file_name);
        $storage->objects->insert("schit", $obj, ['data' => file_get_contents($file_tmp), 'uploadType' => 'media']);
        echo "File has been uploaded";
        echo nl2br("\r\n");
    } else {
        foreach ($errors as $error) {
            echo $error, '<br>';
        }
        echo nl2br("\r\n");
    }
}
?>

        </div>
        <head>
include "Google/Service/Storage.php";
$serviceAccount = "*****@*****.**";
$key_file = "/path/to/keyfile.p12";
$bucket = "my_bucket";
$file_name = "test.txt";
$file_content = "01101010 01110101 01110011 01110100 00100000 01100001 00100000 01110100 01100101 01110011 01110100";
$auth = new Google_Auth_AssertionCredentials($serviceAccount, array('https://www.googleapis.com/auth/devstorage.read_write'), file_get_contents($key_file));
$client = new Google_Client();
$client->setAssertionCredentials($auth);
$storageService = new Google_Service_Storage($client);
/***
 * Write file to Google Storage
 */
try {
    $postbody = array('name' => $file_name, 'data' => $file_content, 'uploadType' => "media");
    $gsso = new Google_Service_Storage_StorageObject();
    $gsso->setName($file_name);
    $result = $storageService->objects->insert($bucket, $gsso, $postbody);
    print_r($result);
} catch (Exception $e) {
    print $e->getMessage();
}
/***
 * Read file from Google Storage
 */
try {
    $object = $storageService->objects->get($bucket, $file_name);
    $request = new Google_Http_Request($object['mediaLink'], 'GET');
    $signed_request = $client->getAuth()->sign($request);
    $http_request = $client->getIo()->makeRequest($signed_request);
    echo $http_request->getResponseBody();
예제 #11
0
 /**
  * {@inheritDoc}
  */
 public function write($key, $content)
 {
     $this->ensureBucketExists();
     $key = $this->computePath($key);
     $obj = new \Google_Service_Storage_StorageObject();
     $obj->name = $key;
     if (isset($this->options['cache-control'])) {
         $obj->setCacheControl($this->options['cache-control']);
     } else {
         $obj->setAcl('project-private');
     }
     $metaData = $this->getMetadata($key);
     unset($metaData['Content-Type']);
     $obj->setMetadata($metaData);
     $processed = false;
     $retryCount = 0;
     while (!$processed) {
         try {
             $obj = $this->service->objects->insert($this->bucket, $obj, array('uploadType' => 'media', 'data' => $content));
             $this->service->objectAccessControls->insert($this->bucket, $key, $this->acl);
             $processed = true;
         } catch (\Google_Service_Exception $gse) {
             $retryCount++;
             if ($retryCount > 6 || $gse->getCode() < 500 && $gse->getCode() > 599) {
                 throw $gse;
                 //Rethrow the exception
             }
             usleep(pow(2, $retryCount) * 500 + rand(1, 1000));
             //Backoff on exception
         }
     }
     return $processed ? $obj->getSize() : false;
 }
예제 #12
0
 private function upload_to_gcs($url, $content, $mime)
 {
     $obj = new Google_Service_Storage_StorageObject();
     $obj->setName($url);
     $this->gcs_storage->objects->insert($this->gcs_bucket, $obj, ['data' => $content, 'uploadType' => 'media', 'mimeType' => $mime]);
     $acl = new Google_Service_Storage_ObjectAccessControl();
     $acl->setEntity('allUsers');
     $acl->setRole('READER');
     $this->gcs_storage->objectAccessControls->insert($this->gcs_bucket, $url, $acl);
 }