PHP Gmail API - Send draft - php

How may I send a draft with GMAIL API and OAuth2.0 via PHP?
In the official docs there is no reference on how to achieve this with PHP.
Based on the Java example, I tried:
$drafts = array();
try {
$draftsResponse = $service->users_drafts->listUsersDrafts('me');
if ($draftsResponse->getDrafts()) {
$drafts = array_merge($drafts, $draftsResponse->getDrafts());
}
}
catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}
var_dump($drafts);
foreach ($drafts as $draft) {
echo 'Draft with ID: ' . $draft->getId() . '<br/>';
$abc = $service->users_drafts->send('me',$draft->getId());
var_dump($abc);
}
But of course I am doing something wrong, because it is not working. The first var_dump() returns all drafts. But nothing else happens after that.
Can you please help me?

You have to create a new Google_Service_Gmail_Draft instance and use that, not just supply the id:
foreach ($drafts as $draft) {
$d = new Google_Service_Gmail_Draft();
$d->setId($draft->getId());
$service->users_drafts->send('me', $d);
}

Related

How to dynamically query couch db

I am using php-on-couch library to retrieve data from couchdb
I want to retrieve basing on where condition. I want data according to the user who is signed in. My code below retrieves a view called accounts but i want to be retrieving without creating views on couchdb. Any help is highly appreciated
try {
$doc = $client->asArray()->getView('accounts', 'accounts');
} catch (Exception $e) {
if ($e->code() == 404) {
echo "View not found\n";
} else {
echo "Error: " . $e->getMessage() . " (errcode=" . $e->getCode() . ")\n";
}
exit(1);
}
print_r($doc);
is there a better way to dynamically create a view on retrieving just like mysql does?
using php-on-couch you can do this
try {
$opts = array("include_docs" => true, "key" => "your user name");
$doc = $client->setQueryParameters($opts)->getView("accounts", "accounts");
} catch (Exception $e) {
if ($e->code() == 404) {
echo "Account not found\n";
} else {
echo "Error: " . $e->getMessage() . " (errcode=" . $e->getCode() . ")\n";
}
exit(1);
}
print_r($doc);
Make sure you emit the username as the key in the accounts view. Couch db will search in all accounts in the view and give you the doc that contains your username.
emit(doc.username, doc);
Hope it helps the rest of you using couchdb in php

Exponential Backoff With Google API PHP Client Library

I am running a web app to get a list of users with Google API PHP Client Library 2.0.3. and save them to a CSV file and at the same time, I am tracking the process on screen. The code I am using is the following:
$pageToken = null;
$optParams = array(
"customer" => "my_customer",
"maxResults" => 500,
"orderBy" => "email",
"sortOrder" => "ASCENDING"
);
try {
$usernum = 0;
do {
if ($pageToken){
$optParams['pageToken'] = $pageToken;
}
$results = $service->users->listUsers($optParams);
$pageToken = $results->getNextPageToken();
$users = $results->getUsers();
foreach ($users as $user) {
$usernum++;
$csvfileusers = array($user->getPrimaryEmail());
fputcsv($savecsv, $csvfileusers);
$usersemails = $user->getPrimaryEmail();
print "<li>".$usernum." - <font color='#9dd7fb'>".$usersemails."</font></li>";
}
} while($pageToken);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
Everything works fine. The problem is that from time to time I am getting { error: { errors: [ { domain: global, reason: backendError, message: Service unavailable. Please try again } ], code: 503, message: Service unavailable. Please try again } }
I know this means that I am sending requests to Google Server too fast hence I need to implement an exponential backoff solution. My problem is that I don't know how to do that. Would someone be kind enough to provide me an example on how to do that using the PHP Client Library? I know that I might be able to figure this out at the long term but if I can get some help I will greatly appreciate it.
Unfortunately, the documentation is lacking for the actual backoff implementation. However, the Google_Task_Runner class outlines the backoff implementation process. You can see how it does it here.
However, based on what you're doign you don't actually want to implement a exponential backoff procedure in general networking terms. You're really wanting to just throttle the request so you don't slam the API. Depending on how many $pageToken you're iterating over, you could just do a sleep before doing the next while iteration.
Additionally, what does $pageToken = $results->getNextPageToken(); become after one request? Becuase you're setting that from the response rather than decrementing it programatically, which may be causing an infinute loop or something of that nature.
So after 20 days of trying and investigating and thanks to the information provided by #kyle, I came up with this exponential backoff solution.
$attemptNum = 1; // retry attempt
$expBackoff = false; // exponential backoff rety indicator
do {
if($attemptNum <= 4) {
try {
$usernum = 1;
do {
if ($pageToken){
$optParams['pageToken'] = $pageToken;
}
$results = $service->users->listUsers($optParams);
$pageToken = $results->getNextPageToken();
$users = $results->getUsers();
foreach ($users as $user) {
$csvfileusers = array($user->getPrimaryEmail());
fputcsv($savecsv, $csvfileusers);
$usersemails = $user->getPrimaryEmail();
print "<li>".$usernum." - <font color='#9dd7fb'>".$usersemails."</font></li>";
$usernum++;
}
} while($pageToken);
} catch (Exception $e) {
$err503ReasonA = "Service unavailable"; // Service unavailable.
$err503ReasonB = "Backend Error"; //Backend Error
$exception = $e->getMessage();
if(strpos($exception, $err503Reason) !== false || strpos($exception, $err503ReasonB) !== false){
$expBackoff = true;
$sleeptime = $retrynum * 1; //retrynum * seconds
sleep($sleeptime);
$retrynum++;
} else {
$expBackoff = false;
print "There was an error -> $exception";
}
}
} else {
$expBackoff = false;
}
} while ($expBackoff);
I have been trying this solution for two days now and it has worked like a charm. Hopefully this might be helpful for someone else. I´m happy now. :)

Parse PHP SDK doesn't return query result

I was able to install the Parse PHP SDK (version 1.1.2) to my project and got through the quick start guide in successfully creating a TestObject. However, when I tried to query the objects, it returns nothing. I'm stuck and don't know where to go from here.
use Parse\ParseQuery;
$query = new ParseQuery('TestObject');
$results = $query->find();
foreach($results as $result){
echo $result->getObjectId() ." - " $result->get("foo") . "\n";
}
You could try it this way:
$myObj= new ParseObject("TestObject");
$myObj->set("objIdd", 1234);
$myObj->set("objName", "My Name");
try {
$myObj->save();
echo 'New object created with objectId: ' . $myObj->getObjectId();
} catch (ParseException $ex) {
// Execute any logic that should take place if the save fails.
// error is a ParseException object with an error code and message.
echo 'Failed to create new object, with error message: ' + $ex->getMessage();
}
//objectId: "XYZABC", objIdd: 1234, objName: "My Name"
$query = new ParseQuery("TestObject");
try {
$myObj = $query->get("XYZABC");
// The object was retrieved successfully.
} catch (ParseException $ex) {
// The object was not retrieved successfully.
// error is a ParseException with an error code and message.
}
Take a look at this guide.

Google Drive PHP API V2 No results when listing

I'm creating a module for joomla that lists the the contents of a given folder. This module works as a service, so no OAuth should be required.
I'm stuck since every request I make has the same answer, no items. So I would like to know if I'm creating the client/service in a wrong way or I may have registered the application in a wrong way.
Here is the code:
// this class is where I have all the IDs from the google console
require_once(dirname(__FILE__) . '/gdrive/config.php');
require_once(dirname(__FILE__) . '/gdrive/gd-v2-php/apiClient.php');
require_once(dirname(__FILE__) . '/gdrive/gd-v2-php/contrib/apiDriveService.php');
$client = new apiClient();
$key = file_get_contents(Config::KEY_FILE);
$client->setClientId(Config::CLIENT_ID);
$client->setUseObjects(true);
$client->setAssertionCredentials(new apiAssertionCredentials(
Config::SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/drive'), $key)
);
$service = new apiDriveService($client);
try {
$parameters = array();
$parameters['maxResults'] = $maxResults;
$files = $service->files->listFiles($parameters);
$items = $files->getItems();
var_dump($items);
$pageToken = $files->getNextPageToken();
} catch (apiServiceException $e) {
print "Error code :" . $e->getCode() . "\n";
// Error message is formatted as "Error calling <REQUEST METHOD> <REQUEST URL>: (<CODE>) <MESSAGE OR REASON>".
print "Error message: " . $e->getMessage() . "\n";
} catch (apiException $e) {
// Other error.
print "An error occurred: (" . $e->getCode() . ") " . $e->getMessage() . "\n";
} catch (Exception $e) {
print "Cannot retrieve the files";
print($e->getMessage());
}
Sorry to ask such a noob question but this is driving me crazy
Thanks
P.S. just for the record, I followed this google-api-php-client/wiki/OAuth2#Service_Accounts
After having a second look to the documentation I found that Google Drive does not support service accounts. I don't know if this is going to change but, with the requirements I have (I need to show in the web is what an end user uploads to a folder (which is public) using the desktop app) I think I cannot use google drive as a valid solution.
I found a solution but I don't like to much since I should have to refresh the token forever Google Drive SDK Service Account Error

Trying to manipulate MS Word bookmarks using PHP and COM

I'm trying to manipulate some fields in a supplied Word 2003 document using the document's own bookmarks using PHP and COM but am getting an error which ever method that I use. If I try to call the Bookmarks directly to substitute the text I get an error: The range cannot be deleted.
function testBkMrkDetails($word, $bookmarkName, $subsTxt) {
try {
$BkMark = $word->ActiveDocument->Bookmarks($bookmarkName);
$range = $BkMark->Range;
if (!$range) {
echo "Range not created ";
}
$range->Text = $subsTxt;
} catch (Exception $e) {
echo "bookmark failed: " . $e->getMessage() . "\n";
}
}
I've searched on Google using the error message and loking for PHP and COM tutorials which appeared to suggest that I look at FormFields so I wrote the following:
function testFormFlds ($word, $bookmarkName, $subsTxt) {
try {
$formField = $word->Selection->FormFields($bookmarkName);
if (!$formField) {
die("Form failed : " . $bookmarkName . " not found\n");
}
$formField->Result($subsTxt);
} catch (Exception $e){
echo "FormField failed: " . $e->getMessage();
}
}
However this keeps telling me that the requested member of the collection does not exists so I'm assuming that I have not called the feild name correctly (it was taen from the document). I would be grateful for some pointers towards solving this and learning more about the underlying technology. Thanks, Iain

Categories