Inserting Events to google calendar from a script - php

Anyone know the proper way to authenticate and publish directly to a calendar without relying on a currently logged in user? Several weeks ago I built a calendar that used the standard Oauth 2.0 protocol but this relied sessions stored by a user's we browser. I have one calendar that I want to pass events to from an application I am writing with a basic PHP framework. I'm more concerned with what are the best practices that others are using. Your answer could be simply, don't do it. Thanks alot.

Use OAuth 2 and the Authorization Code flow (web server flow), with offline enabled. Store the refresh tokens (which last indefinitely until the user has revoked), and you'll be able to upload events to Google Calendar even when the user isn't currently logged in.
More info:
https://developers.google.com/accounts/docs/OAuth2WebServer#offline

try Zend_Gdata_Calendar with this library you are able to insert or get events from any user(with the right username and password obviously) from google calendar and integrate with your own calendar or display it..here a short example:
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient('gmail#user.com', 'gmailpassword', $service);
$service = new Zend_Gdata_Calendar($client);
$query = $service->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
try {
$eventFeed = $service->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getMessage();
}
echo "<ul>";
foreach ($eventFeed as $event) {
echo "<li>" . $event->title . " (Event ID: " . $event->id . ")</li>";
}
echo "</ul>";
$eventURL = "http://www.google.com/calendar/feeds/default/private/full/Dir0FthEpUbl1cGma1lCalendAr";
try {
$event = $service->getCalendarEventEntry($eventURL);
echo 'Evento: ' . $event->getTitle() .'<br>';
echo 'detalles: ' . $event->getContent().'<br>';
foreach ($event->getWhen() as $dato)
{
echo 'inicia: ' . substr($dato->startTime, 0,-19) . ' a las: ' . substr($dato->startTime, 11,-10) .'<br>';
echo 'termina: ' .substr($dato->endTime,0,-19) . ' a las: ' . substr($dato->endTime,11,-10) .'<br>';
}
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getMessage();
}
with this you can add, update, edit or delete events from calendar form any user with mail and password...

Related

Issue creating a service item through QBO API

My QuickBooks Online Application needs to create a Service Item in a QuickBooks Account.
When creating a Service Item through QBO API, I need to query the account for ExpenseAccountRef.Name, ExpenseAccountRef.Value, IncomeAccountRef.Name and IncomeAccountRef.Value first. How can this be done?
I have tried running the following query first but it simply:
$table = "Account";
$entities = $dataService->Query("Select * from $table");
$error = $dataService->getLastError();
if ($error) {
echo "The Status code is: " . $error->getHttpStatusCode() . "\n";
echo "The Helper message is: " . $error->getOAuthHelperError() . "\n";
echo "The Response message is: " . $error->getResponseBody() . "\n";
exit();
}
But it does not provide any of the fields I need listed above.

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

PHP script to pull from Facebook events from multiple pages

Bonjour everyone,
Currently, the script below is on my server as a PHP page (pull.php). It reads the events from a Facebook page using its ID, e.g: 12345678, and outputs them to a file, e.g: 1234568.ics.
What I'd like to ask this community for help with:
1) how would one modify the code below to read from many Facebook pages (an array where I would put in the page ID manually, e.g: 12345678, 24681357, 12348765) and output to many files 12345678.ics, 24682357.ics, 12348765.ics
2) I'm looking for these .ics files to be created and updated (crushed) right on my server, at the same location as where the script runs. The idea is that I'll run a CRON job that would run this script nightly. I then have a plugin on my Facebook page that updates events on the website based on the .ics feed.
CODE:
$access_token = MY_ACCESS_TOKEN;
$page = "12345678";
// We don't want to query the Facebook Graph API over and over, so we'll cache our results. You can force the cache to update by visiting the script and appending "?f=true", otherwise it will only run (rather than display the cache) if the cache is older than 3600 seconds (one hour).
$cache = $page . ".cache";
$f = false;
if($_GET['f'] == "true"){
$f = true;
}
if(!file_exists($cache) || filemtime($cache) <= time()-3600 || $f){
// Get and decode the data - your page's event list - from the API
$graph_url = "https://graph.facebook.com/" . $page . "/events?access_token=" . $access_token;
$data = file_get_contents($graph_url);
$data = json_decode($data);
if(!empty($data->error)){
echo '<b>$data error</b><br />';
echo $data->error->type . " error (" . $data->error->code . "/" . $data->error->error_subcode . "): " . $data->error->message;
exit;
}
// Go through the list of events, and get and decode more detailed information on each event.
foreach ($data->data as $event){
$event_data = file_get_contents("https://graph.facebook.com/" . $event->id . "?access_token=" . $access_token);
$event_data = json_decode($event_data);
if(!empty($event_data->error)){
echo '<b>$event_data error</b><br />';
echo $event_data->error->type . " error (" . $event_data->error->code . "/" . $event_data->error->error_subcode . "): " . $event_data->error->message;
exit;
}
// Store it in an array for later use.
$events[] = $event_data;
}
// We're now done fetching the data from Facebook's Graph API. Now we'll have to create an iCal file.
// This requires the iCalcreator PHP class, which you can downloead from kigkonsult at kigkonsult.se/iCalcreator/index.php
require_once("icalcreator/iCalcreator.class.php");
// Create the calendar, set up some basic properties
$c = new vcalendar(array('unique_id' => $page));
$c->setProperty('X-WR-CALNAME', $page . ' events');
$c->setProperty('X-WR-CALDESC', 'Facebook events for ' . $page);
$c->setProperty('X-WR-TIMEZONE', $events[0]->timezone); // We assume all of the events use the same timezone.
// Loop through the events, create event components in the calendar
foreach($events as $key => $event){
$e[$key] = & $c->newComponent('vevent');
$e[$key]->setProperty('summary', $event->name);
$e[$key]->setProperty('dtstart', $event->start_time);
$e[$key]->setProperty('dtend', $event->end_time);
if (!isset($event->end_time)) {
$e[$key]->setProperty('dtend', $event->start_time);
}
$e[$key]->setProperty('description', $event->description . "\n\nhttp://www.facebook.com/events/" . $event->id);
$e[$key]->setProperty('location', $event->location);
}
// Remove the cache if it exists
if(file_exists($cache)){
unlink($cache);
}
// Open (create) the cache file
if(!$handle = fopen($cache, 'w')){
echo "Cannot open output file: " . $cache;
exit;
}
// Write the calendar to the cache
if(fwrite($handle, $c->createCalendar()) === FALSE){
echo "Cannot write to output file: " . $cache;
exit;
}
// Close the cache file
fclose($handle);
}
// Now we've got the calendar in the cache file, either newly generated and stored there just a few lines ago or from earlier. Now we'll just display it.
header("Content-Type: text/calendar; charset=UTF-8");
header("Content-Disposition: filename=" . $page . ".ics");
require($cache);
?>
Might anyone have a clue how to do this?
Thanks in advance! Upvotes your way if you can help me out!
You can use a FQL query to get results for multiple pages at once, like this:
select eid, creator, name, description, start_time, end_time, timezone, location from event where creator in ({PAGE1_ID}, {PAGE2_ID}, ...) and start_time > now() order by creator asc
You can issue the (URL encoded) query via the
GET /fql?q=...
endpoint like this (replace Page IDs!):
http://graph.facebook.com/fql?q=select%20eid%2C%20creator%2C%20name%2C%20description%2C%20start_time%2C%20end_time%2C%20timezone%2C%20location%20from%20event%20where%20creator%20in%20(1234,5678)%20and%20start_time%20%3E%20now()%20order%20by%20creator%20asc
But then you have to restructure your code a little bit, because the result will look like the following:
{
"data": [
{
"eid": 2289962603,
"creator": 1146614804,
"name": "eventname",
"description": "descr",
"start_time": "2014-05-30T21:00:00+0200",
"end_time": null,
"timezone": "Europe/Berlin",
"location": "thelocation"
},
...
]
}
You then have to react on changes of the value for the creator field, which then indicated that there's a new calendar to be created (creator = page_id)

GooglePlus API - (401) Invalid Credentials error

We have code that was working perfectly to access the Googleplus Api, but now it inexplicably no longer works, instead returning a "(401) Invalid Credentials" error when this line is called:
$me = $plus->people->get('me');
Here is the full code snippet (php):
try
{
$client = new apiClient();
$client->setApplicationName("Google OAuth");
$client->setClientId(GOOGLE_API_CLIENT_ID);
$client->setClientSecret(GOOGLE_API_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_API_REDIRECT_URI);
$client->setDeveloperKey('XXX');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new apiPlusService($client);
$oauth2 = new apiOauth2Service($client);
$client->authenticate();
$token = $client->getAccessToken();
if (isset($token))
$client->setAccessToken($token);
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
}
}
catch (Exception $x)
{
echo "Stack: " . $x->getTraceAsString() . "<br />";
echo "Message: " . $x->getMessage() . "<br />";
echo "File: " . $x->getFile() . "<br />";
echo "Line: " . $x->getLine(). "<br />";
}
I had the same error when user denied access to my aplication, and the token remained in the DB (or session). The API was trying to authenticate using old token. You need to check
if(strpos($x->getMessage(), 'Invalid Credentials')) {
unset($_SESSION['access_token'];
}
and also remove any relevant data from your db.
What fails? the first call to authorize, or the 2nd one to get the token ?
Check the URLs that are sent, it will be easier to inspect the issue.
and: Google might have changed their oAuth APIs?
Everything checks out as far as I can tell, it's possible that something went wrong with the credentials associated with your account.
To verify this, try using another account to access the API or try revoking your application from Google accounts. To revoke your application from your account:
Navigate to this page: https://www.google.com/settings/account
Click the Security link and then click the Manage access button on the bottom of the page.
Find the application that corresponds to your site and click
After your site/application is revoked, go back to your site and then re-authenticate.
This problem is caused when you login from other device using same credentials and then logout .

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

Categories