= 5.1.4 * * You can run this sample both from the command line (CLI) and also * from a web browser. When running through a web browser, only * AuthSub and outputting a list of documents is demonstrated. When * running via CLI, all functionality except AuthSub is available and dependent * upon the command line options passed. Run this script without any * command line options to see usage, eg: * /usr/local/bin/php -f Docs.php * * More information on the Command Line Interface is available at: * http://www.php.net/features.commandline * * NOTE: You must ensure that Zend Framework is in your PHP include * path. You can do this via php.ini settings, or by modifying the * argument to set_include_path in the code below. * * NOTE: As this is sample code, not all of the functions do full error * handling. */ /** * @see Zend_Loader */ require_once 'Zend/Loader.php'; /** * @see Zend_Gdata */ Zend_Loader::loadClass('Zend_Gdata'); /** * @see Zend_Gdata_AuthSub */ Zend_Loader::loadClass('Zend_Gdata_AuthSub'); /** * @see Zend_Gdata_ClientLogin */ Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); /** * @see Zend_Gdata_Docs */ Zend_Loader::loadClass('Zend_Gdata_Docs'); /** * Returns a HTTP client object with the appropriate headers for communicating * with Google using the ClientLogin credentials supplied. * * @param string $user The username, in e-mail address format, to authenticate * @param string $pass The password for the user specified * @return Zend_Http_Client */ function getClientLoginHttpClient($user, $pass) { $service = Zend_Gdata_Docs::AUTH_SERVICE_NAME; $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service); return $client; } // ************************ BEGIN CLI SPECIFIC CODE ************************ /** * Display list of valid commands. * * @param string $executable The name of the current script. This is usually available as $argv[0]. * @return void */ function displayHelp($executable) { echo "Usage: php {$executable} [] [] " . "[ ...]\n\n"; echo "Possible action values include:\n" . "retrieveAllDocuments\n" . "retrieveWPDocs\n" . "retrieveSpreadsheets\n" . "fullTextSearch\n" . "uploadDocument\n"; } /** * Parse command line arguments and execute appropriate function when * running from the command line. * * If no arguments are provided, usage information will be provided. * * @param array $argv The array of command line arguments provided by PHP. * $argv[0] should be the current executable name or '-' if not available. * @param integer $argc The size of $argv. * @return void */ function runCLIVersion($argv, $argc) { if (isset($argc) && $argc >= 2) { # Prepare a server connection if ($argc >= 4) { try { $client = getClientLoginHttpClient($argv[2], $argv[3]); $docs = new Zend_Gdata_Docs($client); } catch (Zend_Gdata_App_AuthException $e) { echo "Error: Unable to authenticate. Please check your"; echo " credentials.\n"; exit(1); } } # Dispatch arguments to the desired method switch ($argv[1]) { case 'retrieveAllDocuments': if ($argc >= 4) { retrieveAllDocuments($docs, false); } else { echo "Usage: php {$argv[0]} {$argv[1]} "; echo " \n\n"; echo "This lists all of the documents in the user's"; echo " account.\n"; } break; case 'retrieveWPDocs': if ($argc >= 4) { //echo "!WP Docs:"; //var_dump($docs); retrieveWPDocs($docs, false); } else { echo "Usage: php {$argv[0]} {$argv[1]} "; echo " \n\n"; echo "This lists all of the word processing documents in"; echo " the user's account.\n"; } break; case 'retrieveSpreadsheets': if ($argc >= 4) { retrieveAllDocuments($docs, false); } else { echo "Usage: php {$argv[0]} {$argv[1]} "; echo " \n\n"; echo "This lists all of the spreadsheets in the user's"; echo " account.\n"; } break; case 'fullTextSearch': if ($argc >= 4) { // Combine all of the query args into one query string. // The command line split the query string on space // characters. $queryString = implode(' ', array_slice($argv, 4)); fullTextSearch($docs, false, $queryString); } else { echo "Usage: php {$argv[0]} {$argv[1]} "; echo " \n\n"; echo "This lists all of the documents which contain the"; echo " query string.\n"; } break; case 'uploadDocument': if ($argc >= 5) { // Pass in the file name of the document to be uploaded. // Since the document is on this machine, we do not need // to set the temporary file name. The temp file name is // used only when uploading to a webserver. uploadDocument($docs, false, $argv[4], null); } else { echo "Usage: php {$argv[0]} {$argv[1]} "; echo " \n\n"; echo "This lists all of the documents which contain the"; echo " query string.\n"; echo "\nExample: php {$argv[0]} {$argv[1]} "; echo " /tmp/testSpreadsheet.ods\n"; } break; default: // Invalid action entered displayHelp($argv[0]); // End switch block } } else { // action left unspecified displayHelp($argv[0]); } } /** * Displays the titles for the Google Documents entries in the feed. In HTML * mode, the titles are links which point to the HTML version of the document. * * @param Zend_Gdata_Docs_DocumentListFeed $feed * @param boolean $html True if output should be formatted for display in * a web browser * @return void */ function printDocumentsFeed($feed, $html) { if ($html) {echo "
    \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 "
  • \n"; } echo "$entry->title\n"; if ($html) {echo "
  • \n";} } if ($html) {echo "
\n";} } /** * Obtain a list of all of a user's docs.google.com documents and print the * titles to the command line. * * @param Zend_Gdata_Docs $client The service object to use for communicating with the Google * Documents server. * @param boolean $html True if output should be formatted for display in a web browser. * @return void */ function retrieveAllDocuments($client, $html) { if ($html) {echo "

Your documents

\n";} $feed = $client->getDocumentListFeed(); printDocumentsFeed($feed, $html); } /** * Obtain a list of all of a user's docs.google.com word processing * documents and print the titles to the command line. * * @param Zend_Gdata_Docs $client The service object to use for communicating with the Google * Documents server. * @param boolean $html True if output should be formatted for display in a web browser. * @return void */ function retrieveWPDocs($client, $html) { if ($html) {echo "

Your word processing documents

\n";} $feed = $client->getDocumentListFeed( 'http://docs.google.com/feeds/documents/private/full/-/document'); printDocumentsFeed($feed, $html); } /** * Obtain a list of all of a user's docs.google.com spreadsheets * documents and print the titles to the command line. * * @param Zend_Gdata_Docs $client The service object to use for communicating with the Google * Documents server. * @param boolean $html True if output should be formatted for display in a web browser. * @return void */ function retrieveSpreadsheets($client, $html) { if ($html) {echo "

Your spreadsheets

\n";} $feed = $client->getDocumentListFeed( 'http://docs.google.com/feeds/documents/private/full/-/spreadsheet'); printDocumentsFeed($feed, $html); } /** * Obtain a list of all of a user's docs.google.com documents * which match the specified search criteria and print the titles to the * command line. * * @param Zend_Gdata_Docs $client The service object to use for communicating with the Google * Documents server. * @param boolean $html True if output should be formatted for display in a web browser. * @param string $query The search query to use * @return void */ function fullTextSearch($client, $html, $query) { if ($html) {echo "

Documents containing $query

\n";} $feed = $client->getDocumentListFeed( 'http://docs.google.com/feeds/documents/private/full?q=' . $query); printDocumentsFeed($feed, $html); } /** * Upload the specified document * * @param Zend_Gdata_Docs $docs The service object to use for communicating with * the Google Documents server. * @param boolean $html True if output should be formatted for display in * a web browser. * @param string $originalFileName The name of the file to be uploaded. The mime type * of the file is determined from the extension on * this file name. For example, test.csv is uploaded * as a comma seperated volume and converted into a * spreadsheet. * @param string $temporaryFileLocation (optional) The file in which the data for the * document is stored. This is used when the file has * been uploaded from the client's machine to the * server and is stored in a temporary file which * does not have an extension. If this parameter is * null, the file is read from the originalFileName. * @return void */ 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 = ''; foreach ($newDocumentEntry->link as $link) { if ($link->getRel() === 'alternate') { $alternateLink = $link->getHref(); } } // Make the title link to the document on docs.google.com. echo "\n"; } echo $newDocumentEntry->title."\n"; if ($html) {echo "\n";} } // ************************ BEGIN WWW SPECIFIC CODE ************************ /** * Writes the HTML prologue for this app. * * NOTE: We would normally keep the HTML/CSS markup separate from the business * logic above, but have decided to include it here for simplicity of * having a single-file sample. * * * @param boolean $displayMenu (optional) If set to true, a navigation menu is displayed at the top * of the page. Default is true. * @return void */ function startHTML($displayMenu = true) { ?> Documents List API Demo
'; echo '← Back
'; } ?>

Almost there...

Before using this demo, you must set an application password to protect your account. You will also need to set your Google Apps credentials in order to communicate with the Google Apps servers.

To continue, open this file in a text editor and fill out the information in the configuration section.

Google Docs Authentication Failed

Authentication with the Google Apps servers failed.

Please open this file in a text editor and make sure your credentials are correct.

{$linkText}"; } /** * Returns the AuthSub URL which the user must visit to authenticate requests * from this application. * * Uses getCurrentUrl() to get the next URL which the user will be redirected * to after successfully authenticating with the Google service. * * @return string AuthSub URL */ function getAuthSubUrl() { $next = getCurrentUrl(); $scope = 'http://docs.google.com/feeds/documents'; $secure = false; $session = true; return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session); } /** * Returns a HTTP client object with the appropriate headers for communicating * with Google using AuthSub authentication. * * Uses the $_SESSION['sessionToken'] to store the AuthSub session token after * it is obtained. The single use token supplied in the URL when redirected * after the user succesfully authenticated to Google is retrieved from the * $_GET['token'] variable. * * @return Zend_Http_Client */ function getAuthSubHttpClient() { global $_SESSION, $_GET; if (!isset($_SESSION['docsSampleSessionToken']) && isset($_GET['token'])) { $_SESSION['docsSampleSessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']); } $client = Zend_Gdata_AuthSub::getHttpClient($_SESSION['docsSampleSessionToken']); return $client; } /** * Returns the full URL of the current page, based upon env variables * * Env variables used: * $_SERVER['HTTPS'] = (on|off|) * $_SERVER['HTTP_HOST'] = value of the Host: header * $_SERVER['SERVER_PORT'] = port number (only used if not http/80,https/443) * $_SERVER['REQUEST_URI'] = the URI after the method of the HTTP request * * @return string Current URL */ 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['SERVER_PORT'] != '' && (($protocol == 'http://' && $_SERVER['SERVER_PORT'] != '80') || ($protocol == 'https://' && $_SERVER['SERVER_PORT'] != '443'))) { $port = ':' . $_SERVER['SERVER_PORT']; } else { $port = ''; } return $protocol . $host . $port . $php_request_uri; } /** * Display the main menu for running in a web browser. * * @return void */ function displayMenu() { ?>

Main Menu

Welcome to the Google Documents List API demo page. Please select from one of the following three options to see a list of commands.

Tip: You can also run this demo from the command line if your system has PHP CLI support enabled.

Logout

Logout successful.

Invalid mode.\n"; echo "

Please check your request and try again.

"; endHTML(true); } } } // Check for an invalid command. If so, display an error and exit. if (!empty($_REQUEST['command'])) { header('HTTP/1.1 400 Bad Request'); startHTML(); echo "

Invalid command.

\n"; echo "

Please check your request and try again.

"; endHTML(true); } // If a menu parameter is available, display a submenu. if (!empty($_REQUEST['menu'])) { switch ($_REQUEST['menu']) { case 'list': startHTML(); displayListMenu(); endHTML(); case 'query': startHTML(); displayQueryMenu(); endHTML(); case 'upload': startHTML(); displayUploadMenu(); endHTML(); case 'logout': startHTML(false); logout(); endHTML(); default: header('HTTP/1.1 400 Bad Request'); startHTML(); echo "

Invalid menu selection.

\n"; echo "

Please check your request and try again.

"; endHTML(true); } } // If we get this far, that means there's nothing to do. Display // the main menu. // If no command was issued and no menu was selected, display the // main menu. startHTML(); displayMenu(); endHTML(); } } /** * Display the menu for running in a web browser. * * @return void */ function displayListMenu() { ?>

List Documents Menu

Retrieve Google Documents Feed

Retrieve the feed for all of your documents.

Retrieve Google Word Processing Documents

Query the documents list feed for all word processing documents.

Retrieve Google Spreadsheets

Query the documents list feed for all spreadsheets.

Query the Documents List Feed

Search the Documents List Feed

Find documents which contain the desired text.

Upload a document

Select a Document to Upload

Upload a file from your computer to Google Documents.

Service Error Encountered

\n"; echo "
" . htmlspecialchars($e->__toString()) . "
"; endHTML(true); } }