In addition to providing some background on the capabilities of the Documents List Data API, this guide provides examples for interacting with the API using the Zend Google Data Client Library. If you're interested in understanding more about the underlying protocol used by the PHP client library to interact with the Documents List, please see the protocol tab.
Important: This Developer's Guide describes how to work with an older version of the Document List Data API protocol. Rest assured we will continue to support this version according to our Terms of Service. However, the latest (and we think greatest) version of the protocol can be found in the left-side navbar -- if it meets your needs, we encourage you to migrate.
This document is intended for developers who want to write client applications using the Google Data PHP client library that can interact with Google Documents.
Google Documents uses Google Accounts for authentication, so if you have a Google account you are all set. Otherwise, you can create a new account.
The Zend Google Data Client Library is available as part of the Zend Framework and also as a separate download. Please use version 1.0.3 or later of the client library to work with the Google Documents List Data API. The client library is only available for use with PHP 5.1.4 or later.
A full working copy of this sample is available in the Zend Framework SVN repository. The sample is located at /framework/standard/trunk/demos/Zend/Gdata/Docs.php.
You can run the sample both from the command line (CLI) and also from a web browser. Run this script without any command line options to see usage, e.g.:
php Docs.php
Before running this sample or developing your own code which uses the Zend Framework, you may need to set the include_path
and load the appropriate classes. For instuctions on setting up your environment to use the library, see the Getting Started with the Google Data PHP Client Library.
Throughout the PHP client library, support has been added for magic setters/getters as a convenience to developers. These allow the properties of a class to be accessed either in a safe way using traditional setter/getter methods or by accessing the properties. For example, if $gdataObject were an instance of an object in this library, the following two lines of code are both completely identical:
$gdataObject->setFoo("bar"); $gdataObject->foo = "bar";
Likewise, these two lines of code are also completely identical:
$baz = $gdataObject->getFoo(); $baz = $gdataObject->foo;
Similarly, we've implemented a "magic" factory method in all service classes, including Zend_Gdata_Docs
. These shield programmers from having to type the large class names mandated for modules within the Zend Framework. As a result, the following blocks of code would also be identical, assuming that the fictitious class Zend_Gdata_Docs_Extensions_Object
existed:
// Traditional instantiation $gdataDocs = new Zend_Gdata_Docs(); $gdataObject = new Zend_Gdata_Docs_Extensions_Object(); // Magic factory instantiation $gdataDocs = new Zend_Gdata_Docs(); $gdataObject = $gdataDocs->newObject();
Both magic setters/getters and magic factories are optional, so feel free to use them or not use them at your convenience.
Other Resources for the Zend Framework Google Data component (Zend_Gdata):
The PHP client library can be used to work with either public or private feeds. The Documents List Data API provides access to private feeds only which require authentication with the documents servers. This can be done via ClientLogin username/password authentication or AuthSub proxy authentication. At this time, Google Documents only offers a private feed for Documents List.
Please see the Google Data APIs Authentication Overview for more information on AuthSub and ClientLogin.
In the sample code below, many of the functions take an authenticated
$gdClient
object as a parameter. The client object is an instance of Zend_Gdata_Docs
and is responsible for performing the API requests to Google servers and sending the appropriate credentials. The AuthSub and ClientLogin sections below illustrate two ways to construct the authenticated client object.
To use ClientLogin (also called "Authentication for Installed
Applications"), create a client using the Zend_Gdata_ClientLogin::getHttpClient
function and passing in the user's credentials. For example:
$user = 'user@gmail.com'; $pass = 'myPassword'; $service = Zend_Gdata_Docs::AUTH_SERVICE_NAME; // predefined service name for Google Documents $httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service); $gdClient = new Zend_Gdata_Docs($httpClient);
For more information about authentication systems, see the Authentication for Installed Applications documentation.
AuthSub proxy authentication is used by web applications which need to authenticate their users to Google accounts. The operator does not need access to the username and password for the Documents user - only special AuthSub tokens are required.
When the user first visits your application, they have not yet been authenticated. In this case, you need to print some text and and a link directing the user to Google to authenticate your request for access to their documents. The PHP Google Data client library provides a function to generate this URL. The code below sets up a link to the AuthSubRequest page.
function getAuthSubUrl() { $next = getCurrentUrl(); $scope = 'http://docs.google.com/feeds/'; $secure = false; $session = true; return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session); }
Notice the parameters sent to the getAuthSubUrl
function:
The URL looks something like this:
https://www.google.com/accounts/AuthSubRequest?scope=http%3A%2F%2Fdocs.google.com%2Ffeeds%2F&session=1&secure=0&next=http%3A%2F%2Fwww.example.com%2Fwelcome.php
The user can then follow the link to Google's site and authenticate to their Google account.
After the user authenticates, they will be redirected back to the next
URL. The URL will have a single-use token value appended to it as a query parameter. The URL looks something like this:
http://www.example.com/welcome.php?token=14a87fe98219731acd516
For security, this token is single-use only, so now you need to exchange this single-use token for a session token. This process is described in the Using AuthSub with the Google Data API Client Libraries. The following code snippet shows how to upgrade the token.
session_start(); function getAuthSubHttpClient() { if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){ echo '<a href="' . getAuthSubUrl() . '">Login!</a>'; exit; } else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) { $_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']); } $httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']); return $httpClient; } $gdClient = new Zend_Gdata_Docs(getAuthSubHttpClient());
In this snippet, the token
element in the session contains the value from the token
query parameter in the URL.
This token value represents a single-use AuthSub token. Since $session=true
was specified above, this token can be exchanged for an AuthSub session token using the getAuthSubSessionToken
method, which calls the AuthSubSessionToken
handler.
You can get a feed containing a list of the currently authenticated user's documents by sending an authenticated GET
request to the following URL:
http://docs.google.com/feeds/documents/private/full
The result is a "meta-feed," a feed that lists all of that user's documents; each entry in the feed represents a document (spreadsheet, word processor document, or presentation) associated with the user. This feed is accessible only using an authentication token.
You can print out a list of the user's documents with the following two functions:
function retrieveAllDocuments($gdClient, $html) { if ($html) {echo "<h2>Your documents</h2>\n";} $feed = $gdClient->getDocumentListFeed(); printDocumentsFeed($feed, $html); } function printDocumentsFeed($feed, $html) { if ($html) {echo "<ul>\n";} // Iterate over the document entries in the feed and display each document's // title. foreach ($feed->entries as $entry) { if ($html) { // Find the URL of the HTML view of the document. $alternateLink = ''; foreach ($entry->link as $link) { if ($link->getRel() === 'alternate') { $alternateLink = $link->getHref(); } } // Make the title link to the document on docs.google.com. echo "<li><a href=\"$alternateLink\">\n"; } echo "$entry->title\n"; if ($html) {echo "</a></li>\n";} } if ($html) {echo "</ul>\n";} }
The resulting Zend_Gdata_Docs_DocumentListFeed
object feed
represents a response from the server. Among other things, this feed
contains a list of Zend_Gdata_Docs_DocumentListEntry
objects (feed->entry
), each of which represents a single
document. DocumentListEntry
encapsulates the information shown in the protocol document.
Files may be uploaded to the Google Documents server using the uploadFile
method in the Zend_Gdata_Docs
client object. The new title for the Google Document and MIME type of the file are sent to the server to facilitate conversion. In the example, the script accepts the file (either uploaded to your own web server as a temporary file, or a local file if the sample is run on the command line), uses the file's original name to determine the MIME type of the file data, and sets the Google Document title to the file name. This file is then sent from your machine to the Google Documents server.
In uploadFile
, the Docs object will lookup the MIME type of the file based on the file name if the MIME type is null
.
function uploadDocument($docs, $html, $originalFileName, $temporaryFileLocation) { $fileToUpload = $originalFileName; if ($temporaryFileLocation) { $fileToUpload = $temporaryFileLocation; } // Upload the file and convert it into a Google Document. The original // file name is used as the title of the document and the mime type // is determined based on the extension on the original file name. $newDocumentEntry = $docs->uploadFile($fileToUpload, $originalFileName, null, Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI); echo "New Document Title: "; if ($html) { // Find the URL of the HTML view of this document. $alternateLink = $newDocumentEntry->getAlternateLink()->getHref(); // Make the title link to the document on docs.google.com. echo "<a href=\"$alternateLink\">\n"; } echo $newDocumentEntry->title."\n"; if ($html) {echo "</a>\n";} }
This example uploads a document, assuming the file to upload is named test.txt
and located in the directory where this script is run. The new document is given the title passed in as the second parameter and the MIME type of the text file in this example is text/plain
. The $newDocumentEntry
variable is a Zend_Gdata_Docs_DocumentListEntry
object containining information about the document that was uploaded, including a direct link to the document. For a similar example showing another way to invoke uploadFile
, see the next section on Uploading a Spreadsheet.
$newDocumentEntry = $docs->uploadFile('test.txt', 'New Test Document', 'text/plain', Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI);
This example uploads a spreadsheet, assuming $fileToUpload
is the path to a spreadsheet and the end of the file name has an extension which can be used to lookup the MIME type. When the document is uploaded, it will be given the title passed in as the second parameter to uploadFile
. The $newDocumentEntry
variable is a Zend_Gdata_Docs_DocumentListEntry
object containing information about the spreadsheet that was uploaded, including a direct link to the spreadsheet.
$filenameParts = explode('.', $fileToUpload); $fileExtension = end($filenameParts); $newDocumentEntry = $docs->uploadFile($fileToUpload, 'A Test Spreadsheet', Zend_Gdata_Docs::lookupMimeType($fileExtension), Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI);
Uploading a presentation is performed in a similar fashion to the above two examples. The essential difference is the MIME type which must correspond to the presentation file you are uploading. This example illustrates uploading a presentation named 'test.ppt'
.
$newDocumentEntry = $docs->uploadFile('test.ppt', 'My New Presentation', 'application/vnd.ms-powerpoint', Zend_Gdata_Docs::DOCUMENTS_LIST_FEED_URI);
To put a document in the trash, perform a DELETE
on the Atom entry representing the document. To trash the new document from the upload examples above, you would execute the following.
$newDocumentEntry->delete();
You can search the Document List using some of the standard Google Data API query parameters. Categories are used to restrict the type of document (word processor document, spreadsheet, or presentation) returned. The full-text query string is used to search the content of all the documents. More detailed information on parameters specific to the Documents List can be found in the Documents List Data API Reference Guide.
In the PHP client library, a Zend_Gdata_Docs_Query
object can be used to construct queries for the Documents List feed. The printDocumentsFeed
function described earlier in this document may be used to display the search results feed.
A list of only word processor documents can be retrieved by using the document
category as follows:
function retrieveWPDocs($gdClient, $html) { if ($html) {echo "<h2>Your word processing documents</h2>\n";} $feed = $gdClient->getDocumentListFeed( 'http://docs.google.com/feeds/documents/private/full/-/document'); printDocumentsFeed($feed, $html); }
A list of only spreadsheets can be retrieved by using the spreadsheet
category as follows:
function retrieveSpreadsheets($gdClient, $html) { if ($html) {echo "<h2>Your spreadsheets</h2>\n";} $feed = $gdClient->getDocumentListFeed( 'http://docs.google.com/feeds/documents/private/full/-/spreadsheet'); printDocumentsFeed($feed, $html); }
A list of only starred presentations can be retrieved by using the presentation
and starred
categories as follows:
function retrieveStarredPresentations($gdClient, $html) { if ($html) {echo "<h2>Your starred presentations</h2>\n";} $feed = $gdClient->getDocumentListFeed( 'http://docs.google.com/feeds/documents/private/full/-/presentation/starred'); printDocumentsFeed($feed, $html); }
It is possible to retrieve documents by matching on their title instead of their entire contents. To do this, set
the title
query parameter in the Zend_Gdata_Docs_Query
object. To match a title exactly, set the
title-exact
parameter to indicate this is the full, explicit title of the document
you want returned. Of course, there could be multiple documents with the same name, so a feed is returned. Searches are case-insensitive.
function retrieveExactTitleMatches($gdClient, $html, $title) { $docsQuery = new Zend_Gdata_Docs_Query(); $docsQuery->setTitle($title); $docsQuery->setTitleExact(true); $feed = $gdClient->getDocumentListFeed($docsQuery); printDocumentsFeed($feed, $html); }
In most cases, a category query which includes the folder name will find the documents in that folder. However, there are some cases where a folder name may need to be disambiguated by performing a scheme qualified query. A list of only documents contained in a folder named "starred" created by the current user with email address $email
can be retrieved by using the following function to disambiguate it from a starred
category query for starred documents as follows:
function retrieveDocsInNamedFolder($gdClient, $html, $folderName, $folderOwnersEmailAddress) { if ($html) {echo "<h2>Your starred presentations</h2>\n";} $folderCategory = '{http://schemas.google.com/docs/2007/folders/' . $folderOwnersEmailAddress . '}' . $folderName; $queryUrl = 'http://docs.google.com/feeds/documents/private/full/-/' . urlencode($folderCategory); $feed = $gdClient->getDocumentListFeed($queryUrl); printDocumentsFeed($feed, $html); } retrieveDocsInNamedFolder($gdClient, $html, 'starred', $email);
To call the above function, you need to pass in the name of the folder and the email address of the folder's creator. For example, to find all document's in Jo's starred folder you could call:
retrieveDocsInNamedFolder($gdClient, true, 'starred', 'jo@gmail.com');
The important distinction here is if you had simply appended the category of "starred" you would get back a list of all starred documents, not the documents in the folder named "starred".
You can search the content of documents by using a Zend_Gdata_Docs_Query
object to construct the feed URI, with the search term being passed in as a parameter.
function fullTextSearch($gdClient, $html, $query) { if ($html) {echo "<h2>Documents containing $query</h2>\n";} $docsQuery = new Zend_Gdata_Docs_Query(); $docsQuery->setQuery($query); $feed = $gdClient->getDocumentListFeed($docsQuery); printDocumentsFeed($feed, $html); }
This searches the entire contents of every document for the string "test" and returns all documents where this string is found.