Google Calendar PHP retrieve events from multiple calendars - php

I was following a tutorial on using the Google Calendar API with the ZEND Framework(http://maestric.com/doc/php/google_calendar_api). I am able to retrieve events from my default calendar by setting the calendar ID: $query->setUser('IDGoesHere');. The problem is I'm not sure how to grab events from all of the calendars I am subscribed to. Is there a way to achieve this or is it not even possible?
Any help is appreciated.
Here is the PHP:
$path = 'ZendGdata/library';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
$user = 'username';
$pass = 'password';
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
try
{
$client = Zend_Gdata_ClientLogin::getHttpClient($user,$pass,$service);
}
catch(Exception $e)
{
echo "Could not connect to calendar.";
die();
}
$gdataCal = new Zend_Gdata_Calendar($client);
$query = $gdataCal->newEventQuery();
$query->setUser('usernameHere');
$query->setVisibility('private');
$query->setSingleEvents(true);
$query->setProjection('full');
$query->setOrderby('starttime');
$query->setSortOrder('ascending');
$query->setMaxResults(20);
$event_list = $gdataCal->getCalendarEventFeed($query);
Grab the events and display them:
foreach ($event_list as $event)
{
echo $event->title ';
echo $event->where[0];
echo $event->content ;
}

You need to setUser to the user id of the secondary calendar.

Related

Bad Request while accesing Gmail API

I'm trying to connect to Gmail but server says:
Uncaught exception 'Google_Service_Exception' with message 'Error calling
GET https://www.googleapis.com/gmail/v1/users/{test}%40gmail.com/messages:
(400) Bad Request' in C:\...\google-api-php-client\src\Google\Http\REST.php on line 110
I can't seem to find the problem. Here's the code:
$google_accounts = $this->getGoogleAccounts();
if (count($google_accounts) > 0) {
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/autoload.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/Client.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/Service/Gmail.php';
$scopes = array(
'https://mail.google.com',
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.modify',
);
$key_file_location = $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/keys/';
foreach ($google_accounts as $one_account) {
if (!empty($one_account->client_id) && !empty($one_account->service_mail) && !empty($one_account->key_file)) {var_dump($one_account);
$key = file_get_contents($key_file_location . $one_account->key_file);
$client = new Google_Client();
$cred = new Google_Auth_AssertionCredentials($one_account->service_mail, $scopes, $key);
$client->setAssertionCredentials($cred);
$client->setClientId($one_account->client_id);
$client->setAccessType('offline_access');
$service = new Google_Service_Gmail($client);
$opt_param = array();
$messagesResponse = $service->users_messages->listUsersMessages($one_account->login, $opt_param);
var_dump($messagesResponse);
}
}
return $list;
}
else {
return false;
}
You need to add:
$cred->sub = $userEmail;
right after creating $cred where $userEmail is the email address of the user you are trying to impersonate. For reference, see the Google Drive Service Account documentation which uses a different scope and API call but is otherwise similar to what you'd want to do with Gmail API.

PHP Google Analytics API - Simple example

I am trying to set some basic example of using Google Analytics with this library: https://github.com/google/google-api-php-client
For starter I have:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_SECRET_API"); //security measures
$service = new Google_Service_Analytics($client);
$results = $service->data_ga;
echo '<pre>';
print_r($results);
echo '</pre>';
Q: How to get data from Google Analytics from this query ?
/*
https://www.googleapis.com/analytics/v3/data/
ga?ids=ga%123456
&dimensions=ga%3Acampaign
&metrics=ga%3Atransactions
&start-date=2013-12-25
&end-date=2014-01-08
&max-results=50
*/
$client->setDeveloperKey("MY_SECRET_API");
First of all, for as far as I experienced this won't work for authentication, you'll need to use a OAuth2 authentication. There are two options to do this, using client ID for web application or using a service account. Authorization api
After you have this, you can make a call like this.
(I use a service account here)
First authenticate:
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
Make a call:
$ids = 'ga:123456'; //your id
$startDate = '2013-12-25';
$endDate = '2014-01-08';
$metrics = 'ga:transactions';
$optParams = array(
'dimensions' => 'ga:campaign',
'max-results' => '50'
);
$results = $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
//Dump results
echo "<h3>Results Of Call:</h3>";
echo "dump of results";
var_dump($results);
echo "results['totalsForAllResults']";
var_dump($results['totalsForAllResults']);
echo "results['rows']";
foreach ($results['rows'] as $item) {
var_dump($item);
}
You will need to do a http get to get the information from the url.
http://www.php.net/manual/en/function.http-get.php
Remember you will still need to add the Oauth2 auth code to the string before you can send that request. This link might help if you dont have auth code already.
https://developers.google.com/analytics/solutions/articles/hello-analytics-api#authorize_access
what you could do is create a new function...
function ga_campaign_transactions($gaEmail, $gaPass, $gProfile, $limit)
{
require_once('classes/google-analytics/gapi.class.php');
$gDimensions = array('campaign');
$gMetrics = array('transactions');
$gSortMetric = NULL;
$gFilter = '';
$gSegment = '';
$gStartDate = '2013-12-25';
$gEndDate = '2014-01-08';
$gStartIndex = 1;
$gMaxResults = $limit;
$ga = new gapi($gaEmail, $gaPass);
$ga->requestReportData($gProfile, $gDimensions, $gMetrics, $gSortMetric, $gFilter, $gSegment, $gStartDate, $gEndDate, $gStartIndex, $gMaxResults);
$gAnalytics_results = $ga->getResults();
//RETURN RESULTS
return $gAnalytics_results;
}
$gProfile = '123456'; // The Profile ID for the account, NOT GA:
$gaEmail = 'YOUR GOOGLE EMAIL'; // Google Email address.
$gaPass = 'YOUR GOOGLE PASSWORD'; // Google Password.
// NOTE: if 2 step login is turned on, create an application password.
$limit = 50;
$ga_campaign_transactions = ga_campaign_transactions($gaEmail, $gaPass, $gProfile, $limit)
//OUTPUT
if(!empty($ga_campaign_transactions))
{
$counter=0;
$gaCampResults= array(); // CREATE ARRAY TO STORE ALL RESULTS
foreach($ga_campaign_transactions as $row)
{
$dim_list = $row->getDimesions();
$met_list = $row->getMetrics();
$gaCampResults[$counter]['campaign'] = $dim_list['campaign'];
$gaCampResults[$counter]['transactions'] = $met_list['transactions'];
$counter++;
}
}
if(!empty($gaCampResults))
{
$totalCampTransactions = count($gaCampResults);
?>
<h2>We Found ( <?php echo number_format($totalCampTransactions,0);?> ) Results</h2>
<ul>
<?php
foreach($gaCampResults as $gaRow){
echo "<li>Campaign:".$gaRow['campaign']." | Transactions: ".$gaRow['transactions']."</li>";
}
?>
</ul>
<?php
}
find Analytics Profile ID
Create Google Application password
Hopefully that puts you on the right track :)
untested this, but similar to what I've been using...
Marty

Google Calendar API batch request PHP

i am trying to send a bunch of events via an Batch Request to Google Calendar.
But i cant figur out how to do. https://developers.google.com/google-apps/calendar/batch doesnt help me.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
$client = new Google_Client();
$client->setUseBatch(true);
$batch = new Google_BatchRequest();
$uri = 'http://www.google.com/calendar/feeds/default/private/full/batch';
$batchContent = file_get_contents('xxxxx/google-api-php-client/batch.xml');
$batch->add($batchContent);
batch.xml contains 2 -items.
Thats all so far. But nothing happened.
I also have tried
$batch->execute()
But thats throws error without message.
My question: How to send a Batch via PHP to Google Calendar ?
I'm using the latest version of Google APIs Client Library for PHP (Google Calendar v.3). I use batch operations for pushing instructor lessons to Google Calendar. Here is my example of code for you (multipleInsert function). Good luck!
<?php
require_once(APPPATH . 'libraries/Google/Client.php');
require_once(APPPATH . 'libraries/Google/Http/Batch.php');
require_once(APPPATH . 'libraries/Google/Service/Calendar.php');
class My_google_calendar
{
...
/** Add single Event for Student */
function addEvent($lesson, $instructor, $return_request = false, $enable_attendees = false)
{
$calendar = $this->getGoogleCalendar(); // get calendar service variable
$lesson_from = date(DATE_RFC3339, $lesson->from);
$lesson_to = date(DATE_RFC3339, $lesson->from + $lesson->duration);
$event = new Google_Service_Calendar_Event();
$event->setSummary('Lesson with student: '$lesson->student_full_name);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($lesson_from);
$start->setTimeZone($this->getGoogleCalendarTimeZone());
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($lesson_to);
$end->setTimeZone($this->getGoogleCalendarTimeZone());
$event->setEnd($end);
$event->setColorId(4);
$description = "...";
$event->setDescription($description);
if (isset($student->email) && $enable_attendees) {
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setResponseStatus('needsAction');
$attendee1->setEmail($student->email);
$attendees = array($attendee1);
$event->setAttendees($attendees);
}
$createdEvent = $this->calendar->events->insert($this->calendar_id, $event, array('fields' => 'id'));
return $return_request ? $createdEvent : $createdEvent->getId();
}
/** Push group of events to the Calendar */
function multipleInsert ($lessons, $instructor)
{
$this->use_batch = true;
$this->client->setUseBatch($this->use_batch);
$batch = new Google_Http_Batch($this->client);
$optParams = array('fields' => 'status,updates');
foreach($lessons as $time => $lesson) {
$lesson = array_shift($group['lessons']);
$req = $this->addEvent($lesson, $instructor, true);
$batch->add($req, $time);
}
}
$results = $batch->execute();
return $results;
}
}
in the newer versions, you should use
$batch = $service->createBatch();
instead of
$batch = new Google_Http_Batch($this->client);
reference

Dropbox for Yii

Has anyone any idea how to tie in the dropbox php api http://code.google.com/p/dropbox-php/ in Yii. I downloaded the source files and put in ext.dropbox and then inserted the following code
$dropbox = Yii::getPathOfAlias('ext.dropbox');
spl_autoload_unregister(array('YiiBase','autoload'));
Yii::registerAutoloader(array('Dropbox_autoload','autoload'));
$consumerKey = '***';
$consumerSecret = '***';
$oauth = new Dropbox_OAuth_PHP($consumerKey, $consumerSecret);
try {
$oauth = new Dropbox_OAuth_PHP($consumerKey, $consumerSecret);
$dropbox = new Dropbox_API($oauth);
$info = $dropbox->getMetaData('Files');
} catch (Exception $e) {
$error = "error: " . $e->getMessage();
}
spl_autoload_register(array('YiiBase','autoload'));
I get the error Fatal error: Class 'CExceptionEvent' not found in *
I'm not sure about Dropbox specifically, but this is how I included SwiftMailer:
Yii::import('swift.classes.Swift', true);
Yii::registerAutoloader(array('Swift','autoload'));
Yii::import('swift.swift_init', true);
where the setPathOfAlias looks like:
Yii::setPathOfAlias('swift', '/var/www/lib');
(I'm using it for other apps, which is why it isn't in the Yii tree. Other libs I keep in the extensions dir and for simple ones, a basic "import" is often enough.)
Try this one:
$dropbox = Yii::getPathOfAlias('ext.dropbox');
spl_autoload_unregister(array('YiiBase','autoload'));
Yii::registerAutoloader(array('Dropbox_autoload','autoload'));
$consumerKey = '***';
$consumerSecret = '***';
$oauth = new Dropbox_OAuth_PHP($consumerKey, $consumerSecret);
try {
$oauth = new Dropbox_OAuth_PHP($consumerKey, $consumerSecret);
$dropbox = new Dropbox_API($oauth);
$info = $dropbox->getMetaData('Files');
} catch (Exception $e) {
$error = "error: " . $e->getMessage();
}
spl_autoload_register(array('YiiBase','autoload'));
Yii::import('swift.classes.Swift', true);
Yii::registerAutoloader(array('Swift','autoload'));
Yii::import('swift.swift_init', true);
Yii::setPathOfAlias('swift', '/var/www/lib');
Also there is a API libary for download in this Dropbox Lib
and also a PHP 5.3 SDK for the Dropbox REST API

how can I append querystring to object?

Google has chanced some things with their calendar API, and now I need to fix some strange symbols that are adding themselves to text. I found this thread which exactly describes the issue I'm dealing with:
http://www.google.com/support/forum/p/Calendar/thread?tid=25ac3d762b235a51&hl=en
The solution is to append "&hl=en" or "?hl=en" to the end of my 'basic' URL feed.
I'm confunsed how to do that though, because I am retrieving the feed as an object with Zend_Gdata:
<?php
// load library
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
Zend_Loader::loadClass('Zend_Http_Client');
// create authenticated HTTP client for Calendar service
$gcal = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$user = "xxxxx";
$pass = "xxxxx";
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $gcal);
$gcal = new Zend_Gdata_Calendar($client);
$query = $gcal->newEventQuery();
$query->setUser('xxxxx#group.calendar.google.com');
$secondary=true;
$query->setVisibility('private');
$query->setProjection('basic');
$query->setOrderby('starttime');
$query->setSortOrder('ascending');
//$query->setFutureevents('true');
$startDate=date('Y-m-d h:i:s');
$endDate="2015-12-31";
$query->setStartMin($startDate);
$query->setStartMax($endDate);
$query->setMaxResults(30);
try {
$feed = $gcal->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getResponse();
}
?>
I tried to do this with no luck:
$query->setProjection('basic?hl=en');
Note: I've not used any of this before so I apologize if this doesn't work :)
The documentation says that getCalendarEventFeed() can take a URL as the parameter.
So we can change this...
$feed = $gcal->getCalendarEventFeed($query);
... to this in order to add the parameter to the query string:
$eventUrl = $query->getQueryUrl() . '?hl=en';
$feed = $gcal->getCalendarEventFeed($eventUrl);
Obviously, this is a simplified example - you should still perform the following two checks:
Make sure $query is an instance of Zend_Gdata_Query before calling getQueryUrl() on it.
Ensure that there are no other query parameters already added to $eventUrl so that we can use &hl=en rather than ?hl=en. You could probably use Zend_Uri for this.

Categories