PHP : Utilizando Google Calendar


You can use the Zend_Gdata_Calendar class to view, create, update, and delete events in the online Google Calendar service.

See » for more information about the Google Calendar API.

Conectando al Calendar Service

El Google Calendar API , como todos los los APIs GData, están basados en el Atom Publishing Protocol (APP), un formato desarrollado en XML para gestionar recursos web. El tráfico entre un cliente y los servidores de Google Calendar tiene lugar sobre HTTP y permite tanto conexiones autenticadas como no autenticadas.

Antes de que cualquier transacción ocurra , es necesario establecer una conexión. Crear una conexión a los servidores de Calendar incluye dos pasos:

  • Crear un cliente HTTP
  • Crear un instancia del servicio Zend_Gdata_Calendar y conectarlo a ese cliente


El Google Calendar API permite acceso a feeds de calendarios tanto públicos como privados:

  • Los feeds públicos no requieren autenticación, pero son de sólo lectura y ofrecen funcionalidad reducidad
  • Los feeds privados ofrecen una funcionalidad más completa pero requiere una conexión autenticada a los servidores de calendar. Hay tres esquemas de autenticación que son soportados por Google Calendar:
    • ClientAuth proporciona autenticación usuario/password directa a los servidores de calendar. Debido a que este esquema requiere que los usuarios proporcionen a tu aplicación su password , este tipo de autenticación es sólo recomendado cuando otros esquemas de autenticación son insuficientes.
    • 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 ofZend_Http_Client will be automatically created.

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

  1. // Parameters for ClientAuth authentication
  2. $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
  3. $user = “”;
  4. $pass = “pa$$w0rd”;
  5. // Create an authenticated HTTP client
  6. $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
  7. // Create an instance of the Calendar service
  8. $service = new Zend_Gdata_Calendar($client);

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

  1. /*
  2. * Retrieve the current URL so that the AuthSub server knows where to
  3. * redirect the user after authentication is complete.
  4. */
  5. function getCurrentUrl()
  6. {
  7.     global $_SERVER;
  8.     // Filter php_self to avoid a security vulnerability.
  9.     $php_request_uri =
  10.         htmlentities(substr($_SERVER[‘REQUEST_URI’],
  11.                             0,
  12.                             strcspn($_SERVER[‘REQUEST_URI’], “nr”)),
  13.                             ENT_QUOTES);
  14.     if (isset($_SERVER[‘HTTPS’]) &&
  15.         strtolower($_SERVER[‘HTTPS’]) == ‘on’) {
  16.         $protocol = ‘https://’;
  17.     } else {
  18.         $protocol = ‘http://’;
  19.     }
  20.     $host = $_SERVER[‘HTTP_HOST’];
  21.     if ($_SERVER[‘HTTP_PORT’] != ” &&
  22.         (($protocol == ‘http://’ && $_SERVER[‘HTTP_PORT’] != ’80’) ||
  23.         ($protocol == ‘https://’ && $_SERVER[‘HTTP_PORT’] != ‘443’))) {
  24.         $port = ‘:’ . $_SERVER[‘HTTP_PORT’];
  25.     } else {
  26.         $port = ”;
  27.     }
  28.     return $protocol . $host . $port . $php_request_uri;
  29. }
  30. /**
  31. * Obtain an AuthSub authenticated HTTP client, redirecting the user
  32. * to the AuthSub server to login if necessary.
  33. */
  34. function getAuthSubHttpClient()
  35. {
  36.     global $_SESSION, $_GET;
  37.     // if there is no AuthSub session or one-time token waiting for us,
  38.     // redirect the user to the AuthSub server to get one.
  39.     if (!isset($_SESSION[‘sessionToken’]) && !isset($_GET[‘token’])) {
  40.         // Parameters to give to AuthSub server
  41.         $next = getCurrentUrl();
  42.         $scope = “”;
  43.         $secure = false;
  44.         $session = true;
  45.         // Redirect the user to the AuthSub server to sign in
  46.         $authSubUrl = Zend_Gdata_AuthSub::getAuthSubTokenUri($next,
  47.                                                              $scope,
  48.                                                              $secure,
  49.                                                              $session);
  50.          header(“HTTP/1.0 307 Temporary redirect”);
  51.          header(“Location: ” . $authSubUrl);
  52.          exit();
  53.     }
  54.     // Convert an AuthSub one-time token into a session token if needed
  55.     if (!isset($_SESSION[‘sessionToken’]) && isset($_GET[‘token’])) {
  56.         $_SESSION[‘sessionToken’] =
  57.             Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET[‘token’]);
  58.     }
  59.     // At this point we are authenticated via AuthSub and can obtain an
  60.     // authenticated HTTP client instance
  61.     // Create an authenticated HTTP client
  62.     $client = Zend_Gdata_AuthSub::getHttpClient($_SESSION[‘sessionToken’]);
  63.     return $client;
  64. }
  65. // -> Script execution begins here <-
  66. // Make sure that the user has a valid session, so we can record the
  67. // AuthSub session token once it is available.
  68. // Create an instance of the Calendar service, redirecting the user
  69. // to the AuthSub server if necessary.
  70. $service = new Zend_Gdata_Calendar(getAuthSubHttpClient());

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

  1. // Create an instance of the Calendar service using an unauthenticated
  2. // HTTP client
  3. $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.

Retrieving A Calendar List

The calendar service supports retrieving a list of calendars for the authenticated user. This is the same list of calendars which are displayed in the Google Calendar UI, except those marked as “hidden” are also available.

The calendar list is always private and must be accessed over an authenticated connection. It is not possible to retrieve another user’s calendar list and it cannot be accessed using MagicCookie authentication. Attempting to access a calendar list without holding appropriate credentials will fail and result in a 401 (Authentication Required) status code.

  1. $service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
  2. $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
  3. $service = new Zend_Gdata_Calendar($client);
  4. try {
  5.     $listFeed= $service->getCalendarListFeed();
  6. } catch (Zend_Gdata_App_Exception $e) {
  7.     echo “Error: ” . $e->getMessage();
  8. }

Calling getCalendarListFeed() creates a new instance of Zend_Gdata_Calendar_ListFeed containing each available calendar as an instance of Zend_Gdata_Calendar_ListEntry. After retrieving the feed, you can use the iterator and accessors contained within the feed to inspect the enclosed calendars.

  1. echo “<h1>Calendar List Feed</h1>”;
  2. echo “<ul>”;
  3. foreach ($listFeed as $calendar) {
  4.     echo “<li>” . $calendar->title .
  5.          ” (Event Feed: ” . $calendar->id . “)</li>”;
  6. }
  7. echo “</ul>”;

Retrieving Events

Like the list of calendars, events are also retrieved using the Zend_Gdata_Calendar service class. The event list returned is of typeZend_Gdata_Calendar_EventFeed and contains each event as an instance of Zend_Gdata_Calendar_EventEntry. As before, the iterator and accessors contained within the event feed instance allow inspection of individual events.


When retrieving events using the Calendar API, specially constructed query URLs are used to describe what events should be returned. TheZend_Gdata_Calendar_EventQuery class simplifies this task by automatically constructing a query URL based on provided parameters. A full list of these parameters is available at the » Queries section of the Google Data APIs Protocol Reference. However, there are three parameters that are worth special attention:

  • User is used to specify the user whose calendar is being searched for, and is specified as an email address. If no user is provided, “default” will be used instead to indicate the currently authenticated user (if authenticated).
  • Visibility specifies whether a users public or private calendar should be searched. If using an unauthenticated session and no MagicCookie is available, only the public feed will be available.
  • Projection specifies how much data should be returned by the server and in what format. In most cases you will want to use the “full” projection. Also available is the “basic” projection, which places most meta-data into each event’s content field as human readable text, and the “composite” projection which includes complete text for any comments alongside each event. The “composite” view is often much larger than the “full” view.

Retrieving Events In Order Of Start Time

The example below illustrates the use of the Zend_Gdata_Query class and specifies the private visibility feed, which requires that an authenticated connection is available to the calendar servers. If a MagicCookie is being used for authentication, the visibility should be instead set to “private-magicCookieValue“, where magicCookieValue is the random string obtained when viewing the private XML address in the Google Calendar UI. Events are requested chronologically by start time and only events occurring in the future are returned.

  1. $query = $service->newEventQuery();
  2. $query->setUser(‘default’);
  3. // Set to $query->setVisibility(‘private-magicCookieValue’) if using
  4. // MagicCookie auth
  5. $query->setVisibility(‘private’);
  6. $query->setProjection(‘full’);
  7. $query->setOrderby(‘starttime’);
  8. $query->setFutureevents(‘true’);
  9. // Retrieve the event list from the calendar server
  10. try {
  11.     $eventFeed = $service->getCalendarEventFeed($query);
  12. } catch (Zend_Gdata_App_Exception $e) {
  13.     echo “Error: ” . $e->getMessage();
  14. }
  15. // Iterate through the list of events, outputting them as an HTML list
  16. echo “<ul>”;
  17. foreach ($eventFeed as $event) {
  18.     echo “<li>” . $event->title . ” (Event ID: ” . $event->id . “)</li>”;
  19. }
  20. echo “</ul>”;

Additional properties such as ID, author, when, event status, visibility, web content, and content, among others are available withinZend_Gdata_Calendar_EventEntry. Refer to the » Zend Framework API Documentation and the » Calendar Protocol Reference for a complete list.

Retrieving Events In A Specified Date Range

To print out all events within a certain range, for example from December 1, 2006 through December 15, 2007, add the following two lines to the previous sample. Take care to remove “$query->setFutureevents(‘true’)“, since futureevents will override startMin andstartMax.

  1. $query->setStartMin(‘2006-12-01’);
  2. $query->setStartMax(‘2006-12-16’);

Note that startMin is inclusive whereas startMax is exclusive. As a result, only events through 2006-12-15 23:59:59 will be returned.

Retrieving Events By Fulltext Query

To print out all events which contain a specific word, for example “dogfood”, use the setQuery() method when creating the query.

  1. $query->setQuery(“dogfood”);

Retrieving Individual Events

Individual events can be retrieved by specifying their event ID as part of the query. Instead of calling getCalendarEventFeed(),getCalendarEventEntry() should be called instead.

  1. $query = $service->newEventQuery();
  2. $query->setUser(‘default’);
  3. $query->setVisibility(‘private’);
  4. $query->setProjection(‘full’);
  5. $query->setEvent($eventId);
  6. try {
  7.     $event = $service->getCalendarEventEntry($query);
  8. } catch (Zend_Gdata_App_Exception $e) {
  9.     echo “Error: ” . $e->getMessage();
  10. }

In a similar fashion, if the event URL is known, it can be passed directly into getCalendarEntry() to retrieve a specific event. In this case, no query object is required since the event URL contains all the necessary information to retrieve the event.

  1. $eventURL = “”
  2.           . “/full/g829on5sq4ag12se91d10uumko”;
  3. try {
  4.     $event = $service->getCalendarEventEntry($eventURL);
  5. } catch (Zend_Gdata_App_Exception $e) {
  6.     echo “Error: ” . $e->getMessage();
  7. }

Creating Events

Creating Single-Occurrence Events

Events are added to a calendar by creating an instance of Zend_Gdata_EventEntry and populating it with the appropriate data. The calendar service instance (Zend_Gdata_Calendar) is then used to used to transparently covert the event into XML and POST it to the calendar server. Creating events requires either an AuthSub or ClientAuth authenticated connection to the calendar server.

At a minimum, the following attributes should be set:

  • Title provides the headline that will appear above the event within the Google Calendar UI.
  • When indicates the duration of the event and, optionally, any reminders that are associated with it. See the next section for more information on this attribute.

Other useful attributes that may optionally set include:

  • Author provides information about the user who created the event.
  • Content provides additional information about the event which appears when the event details are requested from within Google Calendar.
  • EventStatus indicates whether the event is confirmed, tentative, or canceled.
  • Transparency indicates whether the event should be consume time on the user’s free/busy list.
  • WebContent allows links to external content to be provided within an event.
  • Where indicates the location of the event.
  • Visibility allows the event to be hidden from the public event lists.

For a complete list of event attributes, refer to the » Zend Framework API Documentation and the » Calendar Protocol Reference. Attributes that can contain multiple values, such as where, are implemented as arrays and need to be created accordingly. Be aware that all of these attributes require objects as parameters. Trying instead to populate them using strings or primitives will result in errors during conversion to XML.

Once the event has been populated, it can be uploaded to the calendar server by passing it as an argument to the calendar service’sinsertEvent() function.

  1. // Create a new entry using the calendar service’s magic factory method
  2. $event= $service->newEventEntry();
  3. // Populate the event with the desired information
  4. // Note that each attribute is crated as an instance of a matching class
  5. $event->title = $service->newTitle(“My Event”);
  6. $event->where = array($service->newWhere(“Mountain View, California”));
  7. $event->content =
  8.     $service->newContent(” This is my awesome event. RSVP required.”);
  9. // Set the date using RFC 3339 format.
  10. $startDate = “2008-01-20”;
  11. $startTime = “14:00”;
  12. $endDate = “2008-01-20”;
  13. $endTime = “16:00”;
  14. $tzOffset = “-08”;
  15. $when = $service->newWhen();
  16. $when->startTime = “{$startDate}T{$startTime}:00.000{$tzOffset}:00”;
  17. $when->endTime = “{$endDate}T{$endTime}:00.000{$tzOffset}:00”;
  18. $event->when = array($when);
  19. // Upload the event to the calendar server
  20. // A copy of the event as it is recorded on the server is returned
  21. $newEvent = $service->insertEvent($event);

Event Schedules and Reminders

An event’s starting time and duration are determined by the value of its when property, which contains the properties startTime, endTime, and valueString. StartTime and EndTime control the duration of the event, while the valueString property is currently unused.

All-day events can be scheduled by specifying only the date omitting the time when setting startTime and endTime. Likewise, zero-duration events can be specified by omitting the endTime. In all cases, date and time values should be provided in » RFC3339 format.

  1. // Schedule the event to occur on December 05, 2007 at 2 PM PST (UTC-8)
  2. // with a duration of one hour.
  3. $when = $service->newWhen();
  4. $when->startTime = “2007-12-05T14:00:00-08:00”;
  5. $when->endTime=”2007-12-05T15:00:00:00-08:00″;
  6. // Apply the when property to an event
  7. $event->when = array($when);

The when attribute also controls when reminders are sent to a user. Reminders are stored in an array and each event may have up to find reminders associated with it.

For a reminder to be valid, it needs to have two attributes set: method and a time. Method can accept one of the following strings: “alert”, “email”, or “sms”. The time should be entered as an integer and can be set with either the property minutes, hours, days, or absoluteTime. However, a valid request may only have one of these attributes set. If a mixed time is desired, convert to the most precise unit available. For example, 1 hour and 30 minutes should be entered as 90 minutes.

  1. // Create a new reminder object. It should be set to send an email
  2. // to the user 10 minutes beforehand.
  3. $reminder = $service->newReminder();
  4. $reminder->method = “email”;
  5. $reminder->minutes = “10”;
  6. // Apply the reminder to an existing event’s when property
  7. $when = $event->when[0];
  8. $when->reminders = array($reminder);

Creating Recurring Events

Recurring events are created the same way as single-occurrence events, except a recurrence attribute should be provided instead of a where attribute. The recurrence attribute should hold a string describing the event’s recurrence pattern using properties defined in the iCalendar standard (» RFC 2445).

Exceptions to the recurrence pattern will usually be specified by a distinct recurrenceException attribute. However, the iCalendar standard provides a secondary format for defining recurrences, and the possibility that either may be used must be accounted for.

Due to the complexity of parsing recurrence patterns, further information on this them is outside the scope of this document. However, more information can be found in the » Common Elements section of the Google Data APIs Developer Guide, as well as in RFC 2445.

  1. // Create a new entry using the calendar service’s magic factory method
  2. $event= $service->newEventEntry();
  3. // Populate the event with the desired information
  4. // Note that each attribute is crated as an instance of a matching class
  5. $event->title = $service->newTitle(“My Recurring Event”);
  6. $event->where = array($service->newWhere(“Palo Alto, California”));
  7. $event->content =
  8.     $service->newContent(‘ This is my other awesome event, ‘ .
  9.                          ‘ occurring all-day every Tuesday from ‘ .
  10.                          ‘2007-05-01 until 207-09-04. No RSVP required.’);
  11. // Set the duration and frequency by specifying a recurrence pattern.
  12. $recurrence = “DTSTART;VALUE=DATE:20070501rn” .
  13.         “DTEND;VALUE=DATE:20070502rn” .
  14.         “RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20070904rn”;
  15. $event->recurrence = $service->newRecurrence($recurrence);
  16. // Upload the event to the calendar server
  17. // A copy of the event as it is recorded on the server is returned
  18. $newEvent = $service->insertEvent($event);

Using QuickAdd

QuickAdd is a feature which allows events to be created using free-form text entry. For example, the string “Dinner at Joe’s Diner on Thursday” would create an event with the title “Dinner”, location “Joe’s Diner”, and date “Thursday”. To take advantage of QuickAdd, create a new QuickAdd property set to TRUE and store the freeform text as a content property.

  1. // Create a new entry using the calendar service’s magic factory method
  2. $event= $service->newEventEntry();
  3. // Populate the event with the desired information
  4. $event->content= $service->newContent(“Dinner at Joe’s Diner on Thursday”);
  5. $event->quickAdd = $service->newQuickAdd(“true”);
  6. // Upload the event to the calendar server
  7. // A copy of the event as it is recorded on the server is returned
  8. $newEvent = $service->insertEvent($event);

Modifying Events

Once an instance of an event has been obtained, the event’s attributes can be locally modified in the same way as when creating an event. Once all modifications are complete, calling the event’s save() method will upload the changes to the calendar server and return a copy of the event as it was created on the server.

In the event another user has modified the event since the local copy was retrieved, save() will fail and the server will return a 409 (Conflict) status code. To resolve this a fresh copy of the event must be retrieved from the server before attempting to resubmit any modifications.

  1. // Get the first event in the user’s event list
  2. $event = $eventFeed[0];
  3. // Change the title to a new value
  4. $event->title = $service->newTitle(“Woof!”);
  5. // Upload the changes to the server
  6. try {
  7.     $event->save();
  8. } catch (Zend_Gdata_App_Exception $e) {
  9.     echo “Error: ” . $e->getMessage();
  10. }

Deleting Events

Calendar events can be deleted either by calling the calendar service’s delete() method and providing the edit URL of an event or by calling an existing event’s own delete() method.

In either case, the deleted event will still show up on a user’s private event feed if an updateMin query parameter is provided. Deleted events can be distinguished from regular events because they will have their eventStatus property set to “”.

  1. // Option 1: Events can be deleted directly
  2. $event->delete();
  1. // Option 2: Events can be deleted supplying the edit URL of the event
  2. // to the calendar service, if known
  3. $service->delete($event->getEditLink()->href);

Accessing Event Comments

When using the full event view, comments are not directly stored within an entry. Instead, each event contains a URL to its associated comment feed which must be manually requested.

Working with comments is fundamentally similar to working with events, with the only significant difference being that a different feed and event class should be used and that the additional meta-data for events such as where and when does not exist for comments. Specifically, the comment’s author is stored in the author property, and the comment text is stored in the content property.

  1. // Extract the comment URL from the first event in a user’s feed list
  2. $event = $eventFeed[0];
  3. $commentUrl = $event->comments->feedLink->url;
  4. // Retrieve the comment list for the event
  5. try {
  6. $commentFeed = $service->getFeed($commentUrl);
  7. } catch (Zend_Gdata_App_Exception $e) {
  8.     echo “Error: ” . $e->getMessage();
  9. }
  10. // Output each comment as an HTML list
  11. echo “<ul>”;
  12. foreach ($commentFeed as $comment) {
  13.     echo “<li><em>Comment By: ” . $comment->author->name “</em><br/>” .
  14.          $comment->content . “</li>”;
  15. }
  16. echo “</ul>”;