PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Connecting To The Calendar Service

The Google Calendar API, like all GData APIs, is based off of the Atom Publishing Protocol (APP), an XML based format for managing web-based resources. Traffic between a client and the Google Calendar servers occurs over HTTP and allows for both authenticated and unauthenticated connections.

Before any transactions can occur, this connection needs to be made. Creating a connection to the calendar servers involves two steps: creating an HTTP client and binding a Zend_Gdata_Calendar service instance to that client.

Authentication

The Google Calendar API allows access to both public and private calendar feeds. Public feeds do not require authentication, but are read-only and offer reduced functionality. Private feeds offers the most complete functionality but requires an authenticated connection to the calendar servers. There are three authentication schemes that are supported by Google Calendar:

  • ClientAuth provides direct username/password authentication to the calendar servers. Since this scheme requires that users provide your application with their password, this authentication is only recommended when other authentication schemes are insufficient.

  • AuthSub allows authentication to the calendar servers via a Google proxy server. This provides the same level of convenience as ClientAuth but without the security risk, making this an ideal choice for web-based applications.

  • MagicCookie allows authentication based on a semi-random URL available from within the Google Calendar interface. This is the simplest authentication scheme to implement, but requires that users manually retrieve their secure URL before they can authenticate, doesn't provide access to calendar lists, and is limited to read-only access.

The Zend_Gdata library provides support for all three authentication schemes. The rest of this chapter will assume that you are familiar the authentication schemes available and how to create an appropriate authenticated connection. For more information, please see section the Authentication section of this manual or the Authentication Overview in the Google Data API Developer's Guide.

Creating A Service Instance

In order to interact with Google Calendar, this library provides the Zend_Gdata_Calendar service class. This class provides a common interface to the Google Data and Atom Publishing Protocol models and assists in marshaling requests to and from the calendar servers.

Once deciding on an authentication scheme, the next step is to create an instance of Zend_Gdata_Calendar. The class constructor takes an instance of Zend_Http_Client as a single argument. This provides an interface for AuthSub and ClientAuth authentication, as both of these require creation of a special authenticated HTTP client. If no arguments are provided, an unauthenticated instance of Zend_Http_Client will be automatically created.

The example below shows how to create a Calendar service class using ClientAuth authentication:

<?php
// Parameters for ClientAuth authentication
$service Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$user "sample.user@gmail.com";
$pass "pa$$w0rd";

// Create an authenticated HTTP client
$client Zend_Gdata_ClientLogin::getHttpClient($user$pass$service);

// Create an instance of the Calendar service
$service = new Zend_Gdata_Calendar($client);

A Calendar service using AuthSub can be created in a similar, though slightly more lengthy fashion:

<?php
/*
 * Retrieve the current URL so that the AuthSub server knows where to
 * redirect the user after authentication is complete.
 */
function getCurrentUrl()
{
    global 
$_SERVER;

    
// Filter php_self to avoid a security vulnerability.
    
$php_request_uri =
        
htmlentities(substr($_SERVER['REQUEST_URI'],
                            
0,
                            
strcspn($_SERVER['REQUEST_URI'], "\n\r")),
                            
ENT_QUOTES);

    if (isset(
$_SERVER['HTTPS']) &&
        
strtolower($_SERVER['HTTPS']) == 'on') {
        
$protocol 'https://';
    } else {
        
$protocol 'http://';
    }
    
$host $_SERVER['HTTP_HOST'];
    if (
$_SERVER['HTTP_PORT'] != '' &&
        ((
$protocol == 'http://' && $_SERVER['HTTP_PORT'] != '80') ||
        (
$protocol == 'https://' && $_SERVER['HTTP_PORT'] != '443'))) {
        
$port ':' $_SERVER['HTTP_PORT'];
    } else {
        
$port '';
    }
    return 
$protocol $host $port $php_request_uri;
}

/**
 * Obtain an AuthSub authenticated HTTP client, redirecting the user
 * to the AuthSub server to login if necessary.
 */
function getAuthSubHttpClient()
{
    global 
$_SESSION$_GET;

    
// if there is no AuthSub session or one-time token waiting for us,
    // redirect the user to the AuthSub server to get one.
    
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token'])) {
        
// Parameters to give to AuthSub server
        
$next getCurrentUrl();
        
$scope "http://www.google.com/calendar/feeds/";
        
$secure false;
        
$session true;

        
// Redirect the user to the AuthSub server to sign in

        
$authSubUrl Zend_Gdata_AuthSub::getAuthSubTokenUri($next,
                                                             
$scope,
                                                             
$secure,
                                                             
$session);
         
header("HTTP/1.0 307 Temporary redirect");

         
header("Location: " $authSubUrl);

         exit();
    }

    
// Convert an AuthSub one-time token into a session token if needed
    
if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
        
$_SESSION['sessionToken'] =
            
Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
    }

    
// At this point we are authenticated via AuthSub and can obtain an
    // authenticated HTTP client instance

    // Create an authenticated HTTP client
    
$client Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
    return 
$client;
}

// -> Script execution begins here <-

// Make sure that the user has a valid session, so we can record the
// AuthSub session token once it is available.
session_start();

// Create an instance of the Calendar service, redirecting the user
// to the AuthSub server if necessary.
$service = new Zend_Gdata_Calendar(getAuthSubHttpClient());

Finally, an unauthenticated server can be created for use with either public feeds or MagicCookie authentication:

<?php
// Create an instance of the Calendar service using an unauthenticated
// HTTP client

$service = new Zend_Gdata_Calendar();

Note that MagicCookie authentication is not supplied with the HTTP connection, but is instead specified along with the desired visibility when submitting queries. See the section on retrieving events below for an example.

Zend Framework