drive api set appProperties - php

how to set appProperties in google Drive api in php?
$file = new Google_Service_Drive_DriveFile();
$file->setName($f->getFilename());
$file->setMimeType(mime_content_type($f->getPathname()));
$file->setParents(array($dest));
$object = new stdClass();
$object->projecto = 'xpto';
$file->setAppProperties($object);
$data = file_get_contents($f->getPathname());
$createdFile = $driveService->files->create($file, array(
'uploadType' => 'multipart',
'data' => $data
));
i try this:
$file->setAppProperties(array(array('projecto' => 'xpto')));
or this:
$file->setAppProperties(array('projecto' => 'xpto'));
create a file, but dont set properties..

I'm not that much familiar with PHP syntax, but make sure that the setAppproperties is a JSON object. It's indicated on the documentation that its a key-pair value that you can set on the application requesting it. It's even formatted as such in the API Explorer.
You can use Drive API to add your own properties to a Drive file. These properties are stored as key/value pairs on the Drive file.
Do note that by default, the appProperties isn't part of the response object once create has been called. You'll have to specify it on the fields call for it to be part of the response.

Related

Listing buckets in cloud storage project using PHP API

I'm trying to list out all (some, even) of the buckets in my storage project. If I know the name of a bucket, the "bucket" function will get the bucket. But I can't use "buckets" to list the buckets in my project:
$client = new StorageClient(
[
'projectId' => <my project id>,
'keyFile' => json_decode(file_get_contents(<my json file>))
]
);
$bucket_name = 'idx-mls-info-gs-ihouseprd.com';
$one_bucket = $client->bucket( $bucket_name );
print "GOT BUCKET: " . $one_bucket->name() . "\n";
// NOTE: this works
$prefix = 'idx-';
print "Getting buckets (prefix: $prefix)\n";
$buckets = $client->buckets( ['prefix' => $prefix] );
foreach ( $buckets as $bucket )
{
printf('Bucket: %s' . PHP_EOL, $bucket->name());
}
print "done with buckets"
// THIS DOES NOTHING
My service account has the "Storage Admin" role. I am perplexed.
NOTE: I am using PHP 5.6, in case that matters. Composer didn't have a problem installing the GCS library, so I assumed that was ok.
Ok, so I must be missing something. Using my test case of getting a single bucket, I have then used $one_bucket->object(), and successfully gotten an object. But if I try $one_bucket->objects(), I again get nothing. So the multiple case for entities in the GCS is not working for me, whether buckets or objects. Perhaps that's a clue.
Further information:
There is an exception when hitting the iterator (foreach $buckets as $bucket):
exception 'Exception' with message 'exception 'Google\Cloud\Core\Exception\ServiceException' with message '4096:Argument 2 passed to Google\Auth\CredentialsLoader::makeCredentials() must be of the type array, object given, called in /home/httpd/idxv3/vendor/google/cloud-core/src/RequestWrapperTrait.php on line 158 and defined in /home/httpd/idxv3/vendor/google/auth/src/CredentialsLoader.php on line 135' in /home/httpd/idxv3/vendor/google/cloud-core/src/RequestWrapper.php:362
Not sure why the authentication is causing problems.
I've found a link for your first question and I hope this helps guide you. It describes how to list the buckets in your project.
Ok, I found out what the problem was/is. It is in the creation of the storage client. My call the json_decode was missing a parameter. As in my original code, what gets passed into the constructor is a stdClass Object, which is not liked down in the depths of the code. Adding ", true" to the call to json_decode, what gets passed in is then an array, which is desired:
$client = new StorageClient(
[
'projectId' => <my project id>,
'keyFile' => json_decode(file_get_contents(<my json file>), true)
]
);
This fixes the problems I was having. Not sure why I didn't get errors earlier on, like in the constructor.

How to create google sheet with public access enabled using programming

I am trying to create a google sheet with public access enabled using PHP. At this moment, I am generating the google sheet for the newly inserted code. User can download the google sheet.
But now I want to give a default permission public to dynamically created google sheet via code. Is it possible in google sheet?
Here is a code
// Creating new spreadsheet
$spreadsheet = new Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => "$sheet_name"
]
]);
$spreadsheet = $service->spreadsheets->create($spreadsheet, [
'fields' => 'spreadsheetId'
]);
$sheet_id = $spreadsheet->spreadsheetId;
//End Creating new spreadsheet
For creating permissions programmatically you need the method Permissions: create
Once you have the sheet_id, create a permission with permissions->insert()
Specify the role as desired (e.g. reader, writer,...)
For pulib availability of the file - specify the type as anyone
Sample how to implement it in php:
$newPermission= new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
$service->permissions->insert($sheet_id,$newPermission);
If your intention is to use an API key to make changes to a sheet. The answer is you cant.
You need to have authenticated access either though Oauth2 or a service account. using one of the below scopes to make any changes with an API.
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/spreadsheets
Public sheet just means anyone can download and see it and probably make changes via the Sheets web applicaition. Changing it with the API requires access.
You can create a sheet then use the google drive api to update the permissions on the sheet to make it public but again thats not going to enable you to write to it.
Here is the code to set/change permissions of the file. This code can update the permissions of the google spreadsheet too.
I have spent a lot of time. So, anyone who is finding it hard to get any solution to make the google spreadsheet public/any_permission, you can refer to this code.
You can further refer to Google Drive API v3 permissions.
$service = new Google_Service_Drive($client);
$permission = new Google_Service_Drive_Permission();
$permission->setRole( 'reader' );
$permission->setType( 'anyone' );
$service->permissions->create( $spreadsheetId, $permission );

Get publicly accessible URL from Google Cloud after upload PHP

The problem is after I upload an object to my publicly accessible Google Cloud bucket, I want to use the created URL immediately for another service. However, I don't see a way to get the mediaUrl that I could then use. All of the properties on the following method that would give me that are private:
$bucket->upload(
fopen($_FILES['file']['tmp_name'], 'r'),
array('name' => $name)
);
I've already tried var_dump-ing the above method to see if any of the public properties would give me the created URL, but it doesn't even have any public properties.
Here's the code I'm using to upload the data:
$storage = new StorageClient([
'keyFilePath' => 'keyfile_json.json'
]);
$bucket = $storage->bucket('bucket');
$name = 'some/name/path/'.$_POST['name'];
$bucket->upload(
fopen($_FILES['file']['tmp_name'], 'r'),
array('name' => $name)
);
The file is uploading, I just can't get the URL of the actual resource that I can then go use in a different API call to a different service.
How can I get the URL of the resource after it is uploaded?
You have two ways to achieve this:
Creating the URL for public objects using the following sintaxis: https://storage.googleapis.com/[BucketName]/[ObjectName]
Where:
[BucketName] = your bucket
[ObjectName]= name of your uploaded object
If you are using AppEngine Standard Environment, there is a method in the API PHP App Engine API: getPublicUrl(string $gs_filename, boolean $use_https) : string
Where:
$gs_filename, string, The Google Cloud Storage filename, in the format: gs://bucket_name/object_name.
$use_https, boolean, If True then return a HTTPS URL. Note that the development server ignores this argument and returns only HTTP URLs.
Here the API documentation.
You need to build the public Link URL yourself for public objects.
The format is simple https://storage.cloud.google.com/BucketName/ObjectName.

How to set ACL to public-read on AWS-SDK-PHP v3.2 using transfer manager

ok, my first SO question, be nice.
I am having problems finding the answer to this question. yes ive tried
the options for the transfer constructor don't mention any ACL options.
my searches on google come up either blank or for version 2.x
this is my code
$options[] = [
'DEBUG' => true,
];
// Where the files will be transferred to
$dest = 's3://newbucket/'.$UUID;
// Create a transfer object.
$manager = new \Aws\S3\Transfer($s3, $path, $dest, $options );
// Perform the transfer synchronously.
$manager->transfer();
$promise = $manager->promise();
$promise->then(function () {
echo 'Done!';
});
everything uploads ok but the files are not public-read
where/how do i set Public-read on the files uploaded in VERSION 3.2
You can add a 'before' closure to the array of options you're passing to the transfer manager that could handle assigning permissions. Try replacing your manager instantiation code with this:
$manager = new \Aws\S3\Transfer($s3, $path, $dest, [
'before' => function (\Aws\CommandInterface $command) {
if (in_array($command->getName(), ['PutObject', 'CreateMultipartUpload'])) {
$command['ACL'] = 'public-read';
}
},
]);
One way you can do it is set the permissions on the Bucket in the console. under permissions of the bucket you want to set. click 'edit bucket policy'
The other peice of info you will need is how to create the JSON file that you paste in. http://awspolicygen.s3.amazonaws.com/policygen.html if you get an error from AWS's tool just reformat it based on what you see in http://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html
I hope that helps others

Setting ACL Google Cloud Storage via the PHP library

I am using the PHP library for Google API Storage. How do I set the acl parameter (to 'public-read' for example) when inserting a storage object, in order to make an object public via its URI?
I have tried this:
$gso = new \Google_Service_Storage_StorageObject();
$gso->setName($folderAndFileName);
$gso->setAcl('public-read');
but the use of setAcl doesn't seem to have any effect.
I'm not sure if there's an easier way, but this should work:
$acl = new Google_Service_Storage_ObjectAccessControl();
$acl->setEntity('allUsers');
$acl->setRole('READER');
$acl->setBucket('<BUCKET-NAME>');
$acl->setObject('<OBJECT-NAME>');
// $storage being a valid Google_Service_Storage instance
$response = $storage->objectAccessControls->insert('<BUCKET-NAME>', '<OBJECT-NAME>', $acl);
You can see all the possible values here.
Also, this requires the https://www.googleapis.com/auth/devstorage.full_control scope when authenticating.
In order to set the access control for an individual request, you must do the following:
In order to make the file public, the role must be set as "OWNER" and entity as "allUsers"
Documentation can be found here:
https://cloud.google.com/storage/docs/access-control#predefined-project-private
$acl = new Google_Service_Storage_ObjectAccessControl();
$acl->setEntity('allUsers');
$acl->setRole('OWNER');
and then you must apply the ACL to storage object as follows:
$storObj = new Google_Service_Storage_StorageObject();
$storObj ->setAcl(array($acl));
The setAcl function requires an array as it parameter, therefore you add your access control object as the only element in an anonymous array

Categories