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.
Related
I'm using microsoft's graph api to upload files to onedrive. If the upload is successful, I'd like to delete the local file. My code is as follows:
public function testMoveFile()
{
$graph = new Graph();
$graph->setAccessToken($acccess_token);
$response = $graph->createRequest("PUT", "/drives/$drive_id/items/root:/$filename:/content")
->attachBody($content)
->execute();
if ($response->getStatusCode() > 201) {
var_dump($response);
} else {
// remove the file
}
}
The problem is that there doesn't appear to be a getter for the response http status code. When I use var_dump() to examine $response, I can see that there is a private property called _httpStatusCode, but when I try to access it, I get an error because it is private. When I looked through the unit tests, I don't see any checking. Is there another way to do it?
This was easier than I thought. To get the status code, you have to
if ($response->getStatus() > 201) {
I am using sample code from googles site and this throws no exceptions but returns no results.
If I use the API explorer the same data works just fine. I have tried different files (all from google sample code) different settings. All of which give me the same result, Nothing.
function transcribe_sync($content)
{
// set string as audio content
$audio = (new RecognitionAudio())
->setContent($content);
// set config
$encoding = AudioEncoding::LINEAR16;
$sampleRateHertz = 32000;
$languageCode = 'en-US';
$config = (new RecognitionConfig())
->setEncoding($encoding)
->setSampleRateHertz($sampleRateHertz)
->setAudioChannelCount(1)
->setMaxAlternatives(1)
->setLanguageCode($languageCode);
// create the speech client
$client = new SpeechClient();
try {
$response = $client->recognize($config, $audio);
echo $response->getResults()
}
catch (\Exception $e) {
$this->handleError('Error determining recognition. ' . $e->getMessage());
}
finally {
$client->close();
}
My resolution to this issues was the way I was passing the file (don't think the file was being populated correctly or at all). It was weird that I did not get an error. Because of the length of my audio files, I ended up integrating google storage to upload the file () and used:
$audio = (new RecognitionAudio())->setUri("gs://...");
... longRunningRecognize($config, $audio);
Hope this helps someone.
I've a problem using elasticsearch in a php application. The application is built with zend and uses a .env to hold the following configuration:
ELASTICSEARCH_MAX_DOCUMENTS=250
ELASTICSEARCH_MAX_BULK_SIZE=3M
ELASTICSEARCH_HOST=my-elasticsearch.intern.rz
ELASTICSEARCH_PORT=80
ELASTICSEARCH_USER=user
ELASTICSEARCH_PASSWORD=pw
The call to index the new files is part of a import service class and looks like this:
public function flush(FlushInterface $flushInterface = null) {
$bulk = $this->getSearchDocumentBulk();
if (!empty($bulk->getActions())) {
$response = $bulk->send();
$this->resetSearchDocumentBulk();
if (0 === $response->count()) {
$data = $response->getData();
throw new BulkException(isset($data['message']) ? strip_tags($data['message']) : '');
}
}
$this->documentCache = [];
if ($flushInterface instanceof FlushInterface) {
$flushInterface->flush();
}
return $this;
}
protected function getSearchDocumentBulk() {
if (!($this->searchDocumentBulk instanceof Bulk)) {
$this->searchDocumentBulk = new Bulk($this->getSearchClient()->getClient());
$this->searchDocumentBulk->setIndex(self::INDEX);
}
return $this->searchDocumentBulk;
}
I know it's only a short snippet but it's quite difficult to pull out the relevant code. So please let me know if I have to post some more methods.
The application is started by a symfony command and I'm able to curl to elasticsearch (version 5.1) without any errors.
My problem is that no document is indexed. If I check elasticsearch-head I see that there was no data transfer anymore.
But there's also no error, no exception or something like that. The process is completed with 100% (100,000 of 100,000 files imported). So I've no idea what happens or how to find out the bug.
Okay - So I've been looking all over the place to try and correct this problem - But I keep finding different answers, and frankly, it is getting terribly frustrating trying to figure this out. Lemme post some code for you to look at:
PHP Script:
public function addNewCompany(CompanyVO $item)
{
$stmt = mysqli_prepare($this->connection,
"INSERT INTO `companies` ('companyName') VALUES (?);");
$this->throwExceptionOnError();
mysqli_bind_param($stmt, 's', $item->companyName);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$autoid = mysqli_stmt_insert_id($stmt);
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $autoid;
}
Portions of the MXML Main App:
protected function companysignupsheet1_addCompanyEventHandler(event:AddCompanyEvent):void
{
companyservicero.addNewCompany({Data:event.companyData});
}
<s:RemoteObject id="companyservicero"
source="CompanyServices"
destination="addNewCompany"
endpoint = "http://localhost/PHP_RO/public/gateway.php"
result="companyservicero_resultHandler(event)"
fault="companyservicero_faultHandler(event)"/>
A Part of code from Component:
protected function button_submitNewCompany_clickHandler(event:MouseEvent):void
{
var companyData11:CompanyVO = new CompanyVO();
companyData11.companyName = textinput_NewCompanyName.text;
var eventObject:AddCompanyEvent = new AddCompanyEvent("addCompanyEvent", companyData11);
dispatchEvent(eventObject);
}
The Event:
package events
{
import flash.events.Event;
import valueObjects.CompanyVO;
public class AddCompanyEvent extends Event
{
public var companyData:CompanyVO;
public function AddCompanyEvent(type:String, companyData:CompanyVO)
{
super(type);
this.companyData = companyData;
}
}
}
If I need to post more I will be happy to do so. Also - I know it is a bit overkill to try and just send the one text value in this fashion, but there will be much, much more that will go with it when I get it working - I just was trying to focus on where the problem is. Oh - and I don't know if it helps at all...But currently I can retrieve records from the mySQL database this is attached to (although I am not doing that via the RemoteObject way) - I can also add to the same table using the old drag-and-drop (Connect to Data/Services) functionality of an exact copy of the PHP above (although with the information hard coded in (I.E. the CompanyName=testtest)).
And to finish it all off - earlier when I didn't define the datatype for the argument:
public function addNewCompany($item){.....
for addNewCompany - it DID add a record in the database, although it was blank and it would still popup an error message with the whole Channel.Connect, etc..... And now in Zend Server's logs it is saying that the data is getting transferred in a stdClass wrapper and it is needed in CompanyVO datatype.
I am sooo frustrated with this all - I've been stuck with this type of problems for about 2-3 days now and I give up! PLEASE help. Thank you so much for your time and assistance!
-CS
EDIT - MORE INFO
GATEWAY.PHP
<?php
ini_set("display_errors", 1);
$dir = dirname(__FILE__);
$webroot = $_SERVER['DOCUMENT_ROOT'];
$configfile = "$dir/amf_config.ini";
$servicesdir = $dir.'/../services';
$librarydir = $dir.'/../library';
//default zend install directory
$zenddir = $webroot.'/ZendFramework/library';
//Load ini file and locate zend directory
if (file_exists($configfile)) {
$arr = parse_ini_file($configfile, true);
if (isset($arr['zend']['webroot'])) {
$webroot = $arr['zend']['webroot'];
$zenddir = $webroot.'/ZendFramework/library';
}
if (isset($arr['zend']['zend_path'])) {
$zenddir = $arr['zend']['zend_path'];
}
if (isset($arr['zend']['library'])) {
$librarydir = $arr['zend']['library'];
}
if (isset($arr['zend']['services'])) {
$servicesdir = $arr['zend']['services'];
}
}
// Setup include path
// add zend directory, library and services to include path
set_include_path(get_include_path()
.PATH_SEPARATOR.$zenddir
.PATH_SEPARATOR.$librarydir
.PATH_SEPARATOR.$servicesdir);
// Initialize Zend Framework loader
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance()->setFallbackAutoloader(true)- >suppressNotFoundWarnings(true);
// Load configuration
$default_config = new Zend_Config(array("production" => false), true);
$default_config->merge(new Zend_Config_Ini($configfile, 'zendamf'));
$default_config->setReadOnly();
$amf = $default_config->amf;
// Store configuration in the registry
Zend_Registry::set("amf-config", $amf);
// Initialize AMF Server
$server = new Zend_Amf_Server();
$server->setProduction($amf->production);
if (isset($amf->directories)) {
$dirs = $amf->directories->toArray();
foreach ($dirs as $dir) {
if ($dir == "./") {
$server->addDirectory($webroot);
} else
if (realpath("{$webroot}/{$dir}")) {
$server->addDirectory("{$webroot}/{$dir}");
} else
if (realpath($dir)) {
$server->addDirectory(realpath($dir));
}
}
}
// Initialize introspector for non-production
if (! $amf->production) {
$server->setClass('Zend_Amf_Adobe_Introspector', '',
array("config" => $default_config, "server" => $server));
$server->setClass('Zend_Amf_Adobe_DbInspector', '',
array("config" => $default_config, "server" => $server));
}
// Handle request
echo $server->handle();
AMF_CONFIG
[zend]
;set the absolute location path of webroot directory, example:
;Windows: C:\apache\www
;MAC/UNIX: /user/apache/www
webroot = "C:/Zend/Apache2/htdocs"
;set the absolute location path of zend installation directory, example:
;Windows: C:\apache\PHPFrameworks\ZendFramework\library
;MAC/UNIX: /user/apache/PHPFrameworks/ZendFramework/library
zend_path ="C:/Zend/Apache2/htdocs/.metadata/.plugins/org.zend.php.framework.resource/resources/ZendFramework-1/library"
library ="C:/Zend/Apache2/htdocs/PHP_RO/library"
services ="C:/Zend/Apache2/htdocs/PHP_RO/services"
[zendamf]
amf.production = false
amf.directories[]=PHP_RO/services
Channel.Connect.Failed error NetConnection.Call.BadVersion usually happens when PHP echoes an error or warning to the amf response. Flex gets an amf message appended with something like 'warning something went wrong on line X' and can't parse it.
Turn on the network monitor in Flash Builder and view the latest raw response. You will see the error formatted with html tags.
I am having trouble working with Google Docs and Zend Framework 1.11.4.
What I am attempting to do is upload a document to Google Docs, retrieve the HTML content and delete the document. I am working with .doc, .pdf, and .rtf files.
My code so far:
$client = Zend_Gdata_ClientLogin::getHttpClient(
'my#googleDocsEmail.address',
'MyPassword',
Zend_Gdata_Docs::AUTH_SERVICE_NAME
);
$gdClient = new Zend_Gdata_Docs($client);
$newDocumentEntry = $gdClient->uploadFile(
$file,
null,
null,
Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI
);
$cv = file_get_contents($newDocumentEntry->getContent()->getSrc());
$newDocumentEntry->delete();
Everything works fine until the ->delete() method is called, it returns an exception Expected response code 200, got 409
I have been Googling this for a couple of days now but can find no answer, according to Googles documentation this is the correct way to delete a document.
If anyone has any idea as to what I am doing wrong then any help would be very welcome.
Many thanks in advance,
Garry
I was having the same 409 response issue when using the Zend_Gdata_Calendar library. There is an open bug on the Zend framework bugtracker. See http://zendframework.com/issues/browse/ZF-10194
It seems to boil down to the lack of a "If-Match" header being set by the Gdata_App class or one of the child classes in the chain.
To fix it for the Calendar API I've overridden the Zend_Gdata_Calendar class and instantiated my class instead of that one:
class Zend_Gdata_Calendar_Fixed extends \Zend_Gdata_Calendar {
/**
* Overridden to fix an issue with the HTTP request/response for deleting.
* #link http://zendframework.com/issues/browse/ZF-10194
*/
public function prepareRequest($method,
$url = null,
$headers = array(),
$data = null,
$contentTypeOverride = null) {
$request = parent::prepareRequest($method, $url, $headers, $data, $contentTypeOverride);
if($request['method'] == 'DELETE') {
// Default to any
$request['headers']['If-Match'] = '*';
if($data instanceof \Zend_Gdata_App_MediaSource) {
$rawData = $data->encode();
if(isset($rawData->etag) && $rawData->etag != '') {
// Set specific match
$request['headers']['If-Match'] = $rawData->etag;
}
}
}
return $request;
}
}
Then use it:
...
$gdata = new Zend_Gdata_Calendar_Fixed($httpClient);
...
I imagine you could do the same thing but overriding the Zend_Gdata_Docs class instead.