Google Drive SDK downloadFile - What does it do? - php

I am developing in Drupal and using the php code from the Google Drive SDK that is supposed to download a file:
/**
* Download a file's content.
*
* #param Google_DriveService $service Drive API service instance.
* #param File $file Drive File instance.
* #return String The file's content if successful, null otherwise.
*/
function downloadFile($service, $file) {
$downloadUrl = $file->getDownloadUrl();
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
It is returning a successful response code of 200 but I cannot tell that it has actually done anything. However, I can tell from observing my LAN connection status that something of the right size in bytes is being downloaded. I just don't know where it is ending up. I am using Acquia Dev Desktop so I am running the website on my PC, but I cannot find where in the website folder the downloaded file is ending up if it is indeed being stored. I then tried another function that I found here and got similar results. Can someone more familiar with this explain what is happening?
function GetFile($service, $fileId) {
$fileVars = null;
try {
/*
* Retrieve metadata for the file specified by $fileId.
*/
$file = $service->files->get($fileId);
$fileVars = get_object_vars($file);
/*
* Retrieve the file's content using download URL specified in metadata.
*/
$downloadUrl = $file->getDownloadUrl();
error_log('Download URL file from Drive: ' . $downloadUrl);
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
error_log(print_r($httpRequest, 1));
if ($httpRequest->getResponseHttpCode() == 200) {
$content = $httpRequest->getResponseBody();
$fileVars['content'] = $content?($content):'';
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
} catch (apiServiceException $e) {
/*
* Log error and re-throw
*/
error_log('Error retrieving file from Drive: ' . $e->getMessage());
throw $e;
}
return json_encode($fileVars);
}
This method returns the following results:
{"alternateLink":"https:\/\/docs.google.com\/file\/d\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0\/edit?usp=drivesdk","appDataContents":false,"createdDate":"2013-12-05T21:05:03.026Z","defaultOpenWithLink":null,"description":"Flashum mp4","downloadUrl":"https:\/\/doc-0g-50-docs.googleusercontent.com\/docs\/securesc\/apic76cj8gku48a9ogarn9khpku0s46q\/gc9ck66nc600ebdk0ak9f58gkthnnacm\/1386345600000\/08295678552528470768\/15372451357194678536\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0?h=16653014193614665626&e=download&gd=true","editable":true,"embedLink":"https:\/\/video.google.com\/get_player?ps=docs&partnerid=30&docid=0B6ahcE1NPpIaMTJzcFRLMnNiYU0&BASE_URL=https:\/\/docs.google.com\/","etag":"\"maCRbN5nR56FjQPLihEiz9nzpho\/MTM4NjI3NzUwNDU1MA\"","explicitlyTrashed":null,"exportLinks":null,"fileExtension":"mp4","fileSize":"788456","headRevisionId":"0B6ahcE1NPpIaeVJ5b3RxdExvamlDdWNrcGFvWXdvaWg3VU5JPQ","iconLink":"https:\/\/ssl.gstatic.com\/docs\/doclist\/images\/icon_11_video_list.png","id":"0B6ahcE1NPpIaMTJzcFRLMnNiYU0","imageMediaMetadata":null,"indexableText":null,"kind":"drive#file","labels":{"hidden":false,"restricted":false,"starred":false,"trashed":false,"viewed":false},"lastModifyingUser":{"displayName":"C. David Young","isAuthenticatedUser":false,"kind":"drive#user","permissionId":"08295678552528470768","picture":{"url":"https:\/\/lh6.googleusercontent.com\/-tjPzr0pfd_4\/AAAAAAAAAAI\/AAAAAAAAAWc\/DZtQHXrxkgQ\/s64\/photo.jpg"}},"lastModifyingUserName":"C. David Young","lastViewedByMeDate":null,"md5Checksum":"00701d2dd7a1b99e8ebb68cf62305b0d","mimeType":"application\/video","modifiedByMeDate":null,"modifiedDate":"2013-12-05T21:05:04.550Z","openWithLinks":null,"originalFilename":"charlesdavidyoung#gmail.com#test.mp4","ownerNames":["C. David Young"],"owners":[{"displayName":"C. David Young","isAuthenticatedUser":false,"kind":"drive#user","permissionId":"08295678552528470768","picture":{"url":"https:\/\/lh6.googleusercontent.com\/-tjPzr0pfd_4\/AAAAAAAAAAI\/AAAAAAAAAWc\/DZtQHXrxkgQ\/s64\/photo.jpg"}}],"parents":[{"id":"0B6ahcE1NPpIaQlMyWFBPamZIeTA","isRoot":false,"kind":"drive#parentReference","parentLink":"https:\/\/www.googleapis.com\/drive\/v2\/files\/0B6ahcE1NPpIaQlMyWFBPamZIeTA","selfLink":"https:\/\/www.googleapis.com\/drive\/v2\/files\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0\/parents\/0B6ahcE1NPpIaQlMyWFBPamZIeTA"}],"quotaBytesUsed":"788456","selfLink":"https:\/\/www.googleapis.com\/drive\/v2\/files\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0","shared":true,"sharedWithMeDate":null,"thumbnail":null,"thumbnailLink":"https:\/\/lh4.googleusercontent.com\/Ja2DZ3vzXSTn7kY_xY8VmC2N7nCeBrbvnkr-lO4GbMuOmpETwLAYlaC7qr5fOpBTTQ=s220","title":"charlesdavidyoung#gmail.com#test.mp4","userPermission":{"additionalRoles":null,"authKey":null,"etag":"\"maCRbN5nR56FjQPLihEiz9nzpho\/8jq33BWTNkV1S9Wn1TTkFYEVpVc\"","id":"me","kind":"drive#permission","name":null,"photoLink":null,"role":"writer","selfLink":"https:\/\/www.googleapis.com\/drive\/v2\/files\/0B6ahcE1NPpIaMTJzcFRLMnNiYU0\/permissions\/me","type":"user","value":null,"withLink":null},"webContentLink":"https:\/\/docs.google.com\/uc?id=0B6ahcE1NPpIaMTJzcFRLMnNiYU0&export=download","webViewLink":null,"writersCanShare":true,"copyable":true,"content":null}

If you pass to your script a document id it should return you a download link under the field exportLinks. The fact that your exportLinks is null means that you cannot download the file (permissions?).

Related

Symfony2 API - Best way to import and save a CSV file

I need to create an API that receives via POST a .csv file that in a second moment has to be saved to the DB.
This is how I wrote the function:
/**
* #Route("/importCSV", name = "import_csv")
* #Method("POST")
**/
public function importCSVAction(Request $request) {
if ($this->getRequest()->files) {
$type = "csv";
$filename = date('Ymd').'-'.$type.'-filename';
$directory = $this->container->getParameter('kernel.root_dir') . '/../Documents';
$request = $this->get('request');
$data = $request->getContent();
try {
$fs = new Filesystem();
$fs->dumpFile($filename, $data);
move_uploaded_file($filename, $directory);
}
catch(IOException $e) {
return new Response ("File not saved!", 500, array('Content-Type' => 'application/json'));
}
return new Response($data);
}
else return new Response("Error!", 500, array('Content-Type' => 'application/json'));
}
1 One problem is that the file is saved under the web folder and not under Documents as I wanted.
Also, how can I check if the file I'm importing is a .csv file?
2 I searched on the web but I did not found many resources on this subject.
I just want to know if this is generally a correct way to save the .csv file.
Thanks!

PHP Error Class 'Google_Http_Request' not found

I'm trying to download or convert a file from Google Drive. I am using the below code, and I get the error "Class 'Google_Http_Request' not found". I can't seem to find what I'm missing. Am I missing something? A required file?
I'm using php-google-api-php-client (0.6.2-1) [universe].
Thanks.
$file = $service->files->get($drive_id);
//if actual file
//$downloadUrl = $file->getDownloadUrl();
//if a google doc
$downloadUrl = $file->getExportLinks();
if ($downloadUrl) {
$request = new Google_Http_Request($downloadUrl, 'GET', null, null);
$httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
In general, php does not autoload any classes. In basic terms, you would need to require() the right file to load Google_Http_Request, but you will run into more issues as google drive api requires authentication.
I suggest you follow much newer instructions provided on the Google's Developer Center: https://developers.google.com/drive/web/quickstart/php. The quickstart even goes as far as list files.

Google api php How to edit Google table

Good afternoon!
I can download files from the disc with a Google api method:
function downloadFile($service, $downloadUrl,$client) {
if ($downloadUrl) {
$request = new Google_Http_Request($downloadUrl, 'GET', null, null);
$SignhttpRequest = $client->getAuth()->sign($request);
$httpRequest = $client->getIo()->makeRequest($SignhttpRequest);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
But I can not download a file created on the Google Tables. No links in "downloadUrl".
Tell me how you can download and edit the file created on the Google Tables?

Google Drive api setting folder parents

I have been trying to use google api to create first a root folder and then subfolders inside that root folder. However the results have been less than encouraging. Here is the code to create folders:
public function createFolder($name, $parents = array())
{
/** #var $client \Google_Client */
$client = $this->client;
/** #var $service \Google_Service_Drive */
$service = $this->service;
if (is_null($service)) {
throw new Exception("Invalid google api service");
}
if (!$client instanceof \Google_Client) {
throw new Exception("Invalid google api client");
}
if (!isset($_SESSION['access_token'])) {
throw new Exception("No access token found");
}
if (!$client->getAccessToken()) {
throw new Exception("Could not find access token in client");
}
$folder = new \Google_Service_Drive_DriveFile();
$folder->setTitle($name);
$folder->setMimeType('application/vnd.google-apps.folder');
if (!empty($parents)) {
echo "Setting parents of $name to: " . implode(',', $parents);
$folder->setParents($parents);
} else {
echo "\n No parent ids found \n";
}
echo "\n Creating new folder: {$name} \n";
$output = $service->files->insert($folder, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
return $output;
}
Yet whenever I run this script the parents are not set. Instead the subfolders are in a the drive alongside the parent folder.
Also I tried to set the parent flags manually like so:
public function insertFileToFolder($childId, $parentId)
{
if (empty($childId) || empty($parentId)) {
throw new Exception("Invalid parameter");
}
$service = $this->getService();
try {
echo "\n Trying to set subfolders \n";
$parentReference = new \Google_Service_Drive_ParentReference();
$parentReference->setId($parentId);
return $service->parents->insert($childId, $parentReference);
} catch (Exception $ex) {
echo $ex->getMessage();
}
return null;
}
Which does work... kind of. It doesn't "move" the subfolders to the parent but instead either copies them or creates some kind of symlink and the folders appear to be under the parent folder.
Edit: I've confirmed that the insertFileToFolder does not copy the files but instead sets symlinks. Deleting the folder from root also deletes it from parent folder.
Simple question really: What am I missing?
In your function 'insertFileToFolder', instead of using the parents->insert function, use children->insert('FolderID', 'newChild')
You can see an exact implementation on this link: https://developers.google.com/drive/v2/reference/children/insert#examples

Create .CRX (chrome extension / webapp ) file on demand using PHP

I need to create CRX file on the fly. It's for my CMS backend, so it will be just for authenticated users who can install CMS backend as webapp and offer some more privileges to the web app. The problem is, that the backend is used for many domains so creating CRX file for each of them is quite a work. So I figured that it would be easier to just create CRX file on demand which would be generated by PHP using its own domain and probably custom icon.
On the documentation page, they explain the CRX package format. There are many third party libraries that implemented that format. In the following page, you can learn the format and either download a Ruby / Bash script (you can find others too online), and if you want to implement your own packager, you can follow the format described there.
https://developer.chrome.com/extensions/crx
If you really don't want to follow the format, you can let your PHP script do one of the following:
Use Chrome binary chrome.exe --pack-extension=c:\myext --pack-extension-key=c:\myext.pem
Use the Ruby or Bash script from PHP (you can call system commands)
Hope that helps!
Also, for anyone still looking for a way to create a CTX in PHP, look at this question: Create Google Chrome Crx file with PHP
This works for me :D I just change from real path to null without that changes won't work on new chrome :D
/**
* Class CrxGenerator
*
* Create Chrome Extension CRX packages from
* folder & pem private key
*
* Based on CRX format documentation: http://developer.chrome.com/extensions/crx.html
*
* #author: Tomasz Banasiak
* #license: MIT
* #date: 2013-11-03
*/
class CrxGenerator {
const TEMP_ARCHIVE_EXT = '.zip';
private $sourceDir = null;
private $cacheDir = '';
private $privateKeyContents = null;
private $publicKeyContents = null;
private $privateKey = null;
private $publicKey = null;
/**
* #param $file Path to PEM key
* #throws Exception
*/
public function setPrivateKey($file) {
if (!file_exists($file)) {
throw new Exception('Private key file does not exist');
}
$this->privateKeyContents = file_get_contents($file);
$this->privateKey = $file;
}
/**
* #param $file Path to PUB key
* #throws Exception
*/
public function setPublicKey($file) {
if (!file_exists($file)) {
throw new Exception('Private key file does not exist');
}
$this->publicKeyContents = file_get_contents($file);
$this->publicKey = $file;
}
/**
* #param $cacheDir dir specified for caching temporary archives
* #throws Exception
*/
public function setCacheDir($cacheDir) {
if (!is_dir($cacheDir)) {
throw new Exception('Cache dir does not exist!');
}
$this->cacheDir = $cacheDir;
}
/**
* #param $sourceDir Extension source directory
*/
public function setSourceDir($sourceDir) {
$this->sourceDir = $sourceDir;
}
/**
* #param $outputFile path to output file
* #throws Exception
*/
public function generateCrx($outputFile) {
$basename = basename($outputFile);
// First step - create ZIP archive
$zipArchive = $this->cacheDir . DIRECTORY_SEPARATOR . $basename . self::TEMP_ARCHIVE_EXT;
$result = $this->createZipArchive(
$this->sourceDir,
$zipArchive
);
if (!$result) {
throw new Exception('ZIP creation failed');
}
$zipContents = file_get_contents($zipArchive);
// Second step - create file signature
$privateKey = openssl_pkey_get_private($this->privateKeyContents);
openssl_sign($zipContents, $signature, $privateKey, 'sha1');
openssl_free_key($privateKey);
// Create output file
$crx = fopen($outputFile, 'wb');
fwrite($crx, 'Cr24');
fwrite($crx, pack('V', 2));
fwrite($crx, pack('V', strlen($this->publicKeyContents)));
fwrite($crx, pack('V', strlen($signature)));
fwrite($crx, $this->publicKeyContents);
fwrite($crx, $signature);
fwrite($crx, $zipContents);
fclose($crx);
// Clear cache
unset($zipArchive);
}
/**
* #param $source - source dir
* #param $outputFile - output file
* #return bool - success?
*/
private function createZipArchive($source, $outputFile) {
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($outputFile, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = str_replace('\\', '/', $file);
// Exclude "." and ".." folders
if( in_array(substr($file, strrpos($file, '/') + 1), array('.', '..')) ) {
continue;
}
$file = $file;
if (is_dir($file) === true) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true) {
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true) {
$zip->file_get_contents($source);
echo $source;
}
return $zip->close();
}
}
Looks like I have found exactly what I was looking for. Chrome team has made this option to create CRX-less web apps, just by using simple manifest file.
Much easier to create own webapp and publish it on website for installation. And it also solves my problem when I have many websites with a lot of domains and I don't have to create custom CRX file for each domain. I just create small PHP script which creates manifest files on the fly for each domain.

Categories