How to browse files from projects google drive - php

i have created project in google console with service type credentials. I have downloaded p12 key file, and then wrote sample code for inserting file to test it:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
$scopes = array('https://www.googleapis.com/auth/drive');
$accountEmail = 'SECRET';
$accountP12FilePath = './key.p12';
$key = file_get_contents($accountP12FilePath);
$auth = new Google_AssertionCredentials($accountEmail, $scopes, $key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
$service = new Google_DriveService($client);
$file = new Google_DriveFile();
$file->setTitle('Test Title');
$file->setDescription('test description');
$parent = new Google_ParentReference();
$file->setParents(array($parent));
$createdFile = $service->files->insert($file, array(
'data' => 'test data',
'mimeType' => 'text/plain'
));
var_dump($createdFile);
?>
It dumps Google_DriveFile object with many urls. Some of them, like 'downloadUrl', returns 401 Unauthorized error. When I tried 'alternateLink' it showed google drive page with information that i need access, and buttons to request access and to switch account.
It also said that Im currently logged on my account, that was beeing used to create project, and that is visible on Permissions page of the project on the google console page.
How can I access drive that belongs to the project I used in the script ?

Finally found solution, it was missing permissions on file. Its worth to note that passing permission object to the $file object (before insertion) didn't work. I had to insert permission by passing already created file ID and permission object to the $service->permissions->insert method, just like that:
$permission = new Google_Permission();
$permission->setValue('PERSONAL.ACCOUNT#gmail.com');
$permission->setType('user');
$permission->setRole('writer');
$service->permissions->insert($createdFile->getId(), $permission);
Still I wasn't able to actually edit this file. When I opened file with URL
$createdFile->getAlternateLink();
Then I had to reopen that file with google docs. That copied file to my personal account and then I could only edit only that copy of a file, not a base file itself.
I dont know if there is a way to make that files truly editable, but I moved to the dropbox, as google drive API and its documentation SUX.

Related

Service Accounts Authentication not working fr Google Drive - Delete a file Case only

We are using Google Service Accounts in Developers console of PHP API for Drive document.
While checking manually, the owners,editors and then viewers of a document can delete. Then while using Oauth SA, the same viewers or editors of the document cannot delete
Creating a drive file, sharing a file and then setting a document owner of file which all functionality are working fine. We are getting issue while deleting a file by Non-owners of document including editors or viewers of document. But If owner of document deleting means that file deleting without error.
EXAMPLE:
FUNCTION TO GET SERVICE USING SERVICE ACCOUNT
public function get_service_document ($userEmail,$service_id,$scope,$service_filename) {
$key = file_get_contents('application/models/lib/'.$service_filename);
$auth = new Google_Auth_AssertionCredentials(
$service_id,
array($scope),
$key);
$auth->sub = $userEmail;
$client = new Google_Client();
$client->setAssertionCredentials($auth);
return new Google_Service_Drive($client);
}
FUNCTION FOR DELETING A DRIVE FILE
public function deleteDriveFiles(){
$userEmail=xxxxxx#xxxxxxxxx.com;
$service_id=796xxxxxxxxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com;
$scope=https://www.googleapis.com/auth/drive;
$service_filename=xxxxxxxxxx-6088b372ef98.p12;
$this->load->library('Google');
/**GETTING DOCUMENT SERVICE**/
$service = $this->get_service_document();
$fileId="xxxxxxxxxxxxxxxxxxxxx";/** FILE ID OF DOCUMENT**/
try
{
$service->files->delete($fileId);/**
}
catch(Exception $e){
ECHO $e->getMessage();
}
}
The above function showing Error below error:
Error calling DELETE https://www.googleapis.com//drive/v2/files/1ZTd7BxmQErlJTr7OE9uEOOPtIko5UOljOlp-9ampYcA: (403) Insufficient permissions for this file
We tried to solve the above issue using below link but no use
Google PHP Client API: Insufficient Permission
Plz help to solve this issue!

Upload File from App Engine to Google Drive

Eventually, I would like to upload a file to my Google Drive via App Engine php script.
However, following tutorials such as https://developers.google.com/drive/web/quickstart/quickstart-php
force the individual to be signed in. I'm assuming that in this case, I would have to use Service Account credentials.
From here, I uploaded the following code along with the needed API Client Library files
<?php
require_once 'autoload.php';
//require_once 'Auth/AssertionCredentials.php';
require_once 'Client.php';
require_once 'Service/Drive.php';
//
$client = new Google_Client();
$client->setApplicationName("blah-blah-00000");
$client->setClientID("000000000000-00000000000000000000000000000000.apps.googleusercontent.com");
$service = new Google_Service_Drive($client);
// This file location should point to the private key file.
$key = file_get_contents("BlahBlah-000000000000.p12");
$cred = new Google_Auth_AssertionCredentials(
"000000000000-00000000000000000000000000000000#developer.gserviceaccount.com",
// Replace this with the scopes you are requesting.
array('https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file'),
$key
);
$client->setAssertionCredentials($cred);
//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setTitle('HelloWorld');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = "Hello World!";
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
'uploadType' => 'media'
));
//print_r($createdFile);
?>
After visiting the associated appspot.com, the page is blank. At this point, I check the Google Drive associated with the account; however no new files are found.
Am I correct in using a Service account? Provided that this is correct, my next question is am I correctly setting up the credentials? Do I have to impersonate my user account/the account that the App Engine application is setup with?
Am I correct in using a Service account?
Probably not. I see a lot of people using a Service Account when what they should be using is offline access to a standard account.
"At this point, I check the Google Drive associated with the account; however no new files are found". Specifically, people don't realise that a Service Account is NOT associated with their standard account, so naturally when viewing Drive for their standard account, the files from the Service Account aren't there. They're in the Service Account which has no UI.
Provided that this is correct, my next question is am I correctly setting up the credentials?
It isn't. You say " following tutorials such as ... force the individual to be signed in." There aren't any tutorials that show your use case, but that doesn't mean it can't be done. Just that nobody wrote a tutorial on how to do it.
Do I have to impersonate my user account/the account that the App Engine application is setup with?
You need to:-
do a one-time authorize for your account which requests offline access. This will give you a refresh Token which you need to save.
Then use the Refresh Token to request an Access Token when you want to access Drive.
The good news is step 1 doesn't require you to write any code. See How do I authorise an app (web or installed) without user intervention? (canonical ?)
After following pinoyyid's LINK and using an offline OAuth2 refresh token, I updated my code to the following
<?php
require_once 'autoload.php';
require_once 'Client.php';
require_once 'Service/Drive.php';
//
$client = new Google_Client();
// Replace this with your application name.
$client->setApplicationName("00000-00000-00000");
$client->setClientID("000000000000-00000000000000000000000000000000.apps.googleusercontent.com");
$client->setClientSecret("XXXXXXXXXXXXXXXXXXXX");
$client->refreshToken("1/KXXXXXXXXXXXXXXXXXXXXXXXXX");
// Replace this with the service you are using.
$service = new Google_Service_Drive($client);
$_SESSION['service_token'] = $client->getAccessToken();
//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setTitle('HelloWorld');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = "Hello World!";
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
'uploadType' => 'media'
));
?>

Is the installation tutorial outdated? Google API novice here

https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample
Trying to run the quickstart.php file i find that it does absolutelly nothing.
Checking the code and comparing it to my files i see the folder and files names are different. I download the library from github and i also noticed the src folder was updated 2 days ago.
I tried just to chage them to make the quickstart run but yet it does nothing.
Im trying to authorize google drive to upload files from a page.
I already got my secret key and id, hello world and all those steps, i just cant make the quickstart to run.
I dont know how to use subversion, i just want to upload files, can somebody help me? what am i missing?
<?php
require_once 'google-api-php-client/src/Google_Client.php'; //incorrect files
require_once 'google-api-php-client/src/contrib/Google_DriveService.php'; /incorrect files
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('already changed');
$client->setClientSecret('already changed');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
So i found this:
Submitting file to Google drive
The code is indeed outdated, i did these changes:
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/contrib/Google/Service.php';
instead of Google_DriveService just use Google_Service.
implement the code posted by user3407337 on the previous link.
That should do the trick.

Google_Service_Drive retrieveListOfAllFiles only returning one file

When I run the API from php the only item returned is the "How to get started with Drive" file which isn't in the folder, but when I run the retrieveListOfAllFiles() from the API webpage I see all the files in the drive. Here is the code.
set_include_path(ABSPATH . "path-to/api/google-api-php-client/src/");
require_once "Google/Client.php";
require_once "Google/Service/Drive.php";
require_once "Google/Auth/OAuth2.php";
require_once "Google/Auth/AssertionCredentials.php";
define('CLIENT_ID', 'xxxxx');
define('SERVICE_ACCOUNT_NAME', 'xxxxx');
$key = file_get_contents(ABSPATH . "path-to-.p12");
$scopes = array('https://www.googleapis.com/auth/drive.readonly');
$client = new Google_Client();
$client->setApplicationName("xxxx");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$auth = new Google_Auth_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
$scopes,
$key
);
$client->setAssertionCredentials($auth);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($auth);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Drive($client);
$files = retrieveAllFiles($service);
Files only returns the "how to get started with drive" file - where as the API test from this page: https://developers.google.com/drive/v2/reference/files/list returns all the files in the drive.
The Ids are correct, the .p12 file is new and loading, I have no idea what is going wrong.
I have also noticed that if I var_dump() the output of this
dump($service->files->listFiles(array()));
I also only get the single "how to get started with drive" file. So it seems like even though I'm not getting any OAuth2 errors, and getting a key token, etc, the drive I want to list the files from is not being accessed.
Problem resolved. A folder from the Drive must be shared with the API user - the email ending in #developer.gserviceaccount.com - which I didn't see in the docs anywhere... maybe I'm blind. But those API docs are pretty out of date, it seems.

Can't Upload File to Google Cloud Storage with PHP Client Library

I want this script to upload a text file to a bucket in my Google Cloud Storage Account. I'm using the PHP Client Library, specifically the objects.insert method. The script seems to work up until I actually call the insert method (if I cancel that line out, then I can at least see the results from the var_dump). If I call the method, I get a HTTP 500 - Internal Server Error (and the file does not make it to my Cloud Storage account).
Some things to note:
This script is for a service account
The text file is in the same folder as this script
I think there's something wrong with the way I'm calling insert, but I can't figure it out. I'd appreciate any suggestions on how to make this script work so that the text file uploads.
Here's the code:
<?php
require_once 'lib/src/Google_Client.php';
require_once 'lib/src/contrib/Google_StorageService.php';
define("CLIENT_ID", "MY-CLIENT-ID");
define("SERVICE_ACCOUNT_NAME", "MY-SERVICE-ACCOUNT-NAME");
define("KEY_FILE", "/path/to/privatekey.p12");
$client = new Google_Client();
$client->setApplicationName("Google Cloud Storage Test Connection");
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/devstorage.read_write'),
$key)
);
$client->setClientId(CLIENT_ID);
//Define Storage Service
$storageService = new Google_StorageService($client);
$objects = $storageService -> objects;
//Define Storage Object
$gso = new Google_StorageObject ();
$gso-> setName('myObj');
//Define Storage Object Media
$gsoMedia = new Google_StorageObjectMedia ();
$gsoMedia-> setContentType('text/plain');
$gsoMedia-> setData(file_get_contents('Test.txt'));
//Link Storage Object Media to Storage Object
$gso-> setMedia($gsoMedia);
//Upload to Cloud Storage
$result = $objects->insert(/*MY_BUCKET*/, $gso);
var_dump($gso);
?>

Categories