Commit a2457b5f authored by Robin Appelman's avatar Robin Appelman
Browse files

Merge pull request #6989 from AdamWill/google-1

Migrate Google Drive external storage app to v1.0.6-beta of the google-api-php-client library
parents 4ed0a418 c237acb3
This product contains the following libraries:
XRDS-Simple library from http://code.google.com/p/diso/
Apache License 2.0
Google APIs Client Library for PHP
=====================================
== Description
The Google API Client Library enables you to work with Google APIs such as Google+, Drive, Tasks, or Latitude on your server.
Requirements:
PHP 5.2.x or higher [http://www.php.net/]
PHP Curl extension [http://www.php.net/manual/en/intro.curl.php]
PHP JSON extension [http://php.net/manual/en/book.json.php]
Project page:
http://code.google.com/p/google-api-php-client
OAuth 2 instructions:
http://code.google.com/p/google-api-php-client/wiki/OAuth2
Report a defect or feature request here:
http://code.google.com/p/google-api-php-client/issues/entry
Subscribe to project updates in your feed reader:
http://code.google.com/feeds/p/google-api-php-client/updates/basic
Supported sample applications:
http://code.google.com/p/google-api-php-client/wiki/Samples
== Basic Example
<?php
require_once 'path/to/src/Google_Client.php';
require_once 'path/to/src/contrib/apiBooksService.php';
$client = new Google_Client();
$service = new Google_BooksService($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
foreach ($results['items'] as $item) {
print($item['volumeInfo']['title'] . '<br>');
}
[![Build Status](https://travis-ci.org/google/google-api-php-client.svg)](https://travis-ci.org/google/google-api-php-client)
# Google APIs Client Library for PHP #
## Description ##
The Google API Client Library enables you to work with Google APIs such as Google+, Drive, or YouTube on your server.
## Beta ##
This library is in Beta. We're comfortable enough with the stability and features of the library that we want you to build real production applications on it. We will make an effort to support the public and protected surface of the library and maintain backwards compatibility in the future. While we are still in Beta, we reserve the right to make incompatible changes. If we do remove some functionality (typically because better functionality exists or if the feature proved infeasible), our intention is to deprecate and provide ample time for developers to update their code.
## Requirements ##
* [PHP 5.2.1 or higher](http://www.php.net/)
* [PHP JSON extension](http://php.net/manual/en/book.json.php)
*Note*: some features (service accounts and id token verification) require PHP 5.3.0 and above due to cryptographic algorithm requirements.
## Developer Documentation ##
http://developers.google.com/api-client-library/php
## Installation ##
For the latest installation and setup instructions, see [the documentation](https://developers.google.com/api-client-library/php/start/installation).
## Basic Example ##
See the examples/ directory for examples of the key client features.
```PHP
<?php
require_once 'google-api-php-client/autoload.php'; // or wherever autoload.php is located
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("YOUR_APP_KEY");
$service = new Google_Service_Books($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
```
## Frequently Asked Questions ##
### What do I do if something isn't working? ###
For support with the library the best place to ask is via the google-api-php-client tag on StackOverflow: http://stackoverflow.com/questions/tagged/google-api-php-client
If there is a specific bug with the library, please file a issue in the Github issues tracker, including a (minimal) example of the failing code and any specific errors retrieved. Feature requests can also be filed, as long as they are core library requests, and not-API specific: for those, refer to the documentation for the individual APIs for the best place to file requests. Please try to provide a clear statement of the problem that the feature would address.
### How do I contribute? ###
We accept contributions via Github Pull Requests, but all contributors need to be covered by the standard Google Contributor License Agreement. You can find links, and more instructions, in the documentation: https://developers.google.com/api-client-library/php/contribute
### Why do you still support 5.2? ###
When we started working on the 1.0.0 branch we knew there were several fundamental issues to fix with the 0.6 releases of the library. At that time we looked at the usage of the library, and other related projects, and determined that there was still a large and active base of PHP 5.2 installs. You can see this in statistics such as the PHP versions chart in the WordPress stats: http://wordpress.org/about/stats/. We will keep looking at the types of usage we see, and try to take advantage of newer PHP features where possible.
### Why does Google_..._Service have weird names? ###
The _Service classes are generally automatically generated from the API discovery documents: https://developers.google.com/discovery/. Sometimes new features are added to APIs with unusual names, which can cause some unexpected or non-standard style naming in the PHP classes.
### How do I deal with non-JSON response types? ###
Some services return XML or similar by default, rather than JSON, which is what the library supports. You can request a JSON response by adding an 'alt' argument to optional params that is normally the last argument to a method call:
```
$opt_params = array(
'alt' => "json"
);
```
## Code Quality ##
Copy the ruleset.xml in style/ into a new directory named GAPI/ in your
/usr/share/php/PHP/CodeSniffer/Standards (or appropriate equivalent directory),
and run code sniffs with:
phpcs --standard=GAPI src/
......@@ -14,23 +14,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "Google_AuthNone.php";
require_once "Google_OAuth2.php";
require_once "Google/Http/Request.php";
/**
* Abstract class for the Authentication in the API client
* @author Chris Chabot <chabotc@google.com>
*
*/
abstract class Google_Auth {
abstract public function authenticate($service);
abstract public function sign(Google_HttpRequest $request);
abstract public function createAuthUrl($scope);
abstract public function getAccessToken();
abstract public function setAccessToken($accessToken);
abstract public function setDeveloperKey($developerKey);
abstract public function refreshToken($refreshToken);
abstract public function revokeToken();
abstract class Google_Auth_Abstract
{
/**
* An utility function that first calls $this->auth->sign($request) and then
* executes makeRequest() on that signed request. Used for when a request
* should be authenticated
* @param Google_Http_Request $request
* @return Google_Http_Request $request
*/
abstract public function authenticatedRequest(Google_Http_Request $request);
abstract public function sign(Google_Http_Request $request);
}
......@@ -15,12 +15,17 @@
* limitations under the License.
*/
require_once "Google/Auth/OAuth2.php";
require_once "Google/Signer/P12.php";
require_once "Google/Utils.php";
/**
* Credentials object used for OAuth 2.0 Signed JWT assertion grants.
*
* @author Chirag Shah <chirags@google.com>
*/
class Google_AssertionCredentials {
class Google_Auth_AssertionCredentials
{
const MAX_TOKEN_LIFETIME_SECS = 3600;
public $serviceAccountName;
......@@ -34,6 +39,7 @@ class Google_AssertionCredentials {
* @link http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
*/
public $prn;
private $useCache;
/**
* @param $serviceAccountName
......@@ -42,8 +48,9 @@ class Google_AssertionCredentials {
* @param string $privateKeyPassword
* @param string $assertionType
* @param bool|string $sub The email address of the user for which the
* application is requesting delegated access.
*
* application is requesting delegated access.
* @param bool useCache Whether to generate a cache key and allow
* automatic caching of the generated token.
*/
public function __construct(
$serviceAccountName,
......@@ -51,7 +58,9 @@ class Google_AssertionCredentials {
$privateKey,
$privateKeyPassword = 'notasecret',
$assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
$sub = false) {
$sub = false,
$useCache = true
) {
$this->serviceAccountName = $serviceAccountName;
$this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
$this->privateKey = $privateKey;
......@@ -59,13 +68,32 @@ class Google_AssertionCredentials {
$this->assertionType = $assertionType;
$this->sub = $sub;
$this->prn = $sub;
$this->useCache = $useCache;
}
/**
* Generate a unique key to represent this credential.
* @return string
*/
public function getCacheKey()
{
if (!$this->useCache) {
return false;
}
$h = $this->sub;
$h .= $this->assertionType;
$h .= $this->privateKey;
$h .= $this->scopes;
$h .= $this->serviceAccountName;
return md5($h);
}
public function generateAssertion() {
public function generateAssertion()
{
$now = time();
$jwtParams = array(
'aud' => Google_OAuth2::OAUTH2_TOKEN_URI,
'aud' => Google_Auth_OAuth2::OAUTH2_TOKEN_URI,
'scope' => $this->scopes,
'iat' => $now,
'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
......@@ -86,16 +114,22 @@ class Google_AssertionCredentials {
* @param array $payload
* @return string The signed JWT.
*/
private function makeSignedJwt($payload) {
private function makeSignedJwt($payload)
{
$header = array('typ' => 'JWT', 'alg' => 'RS256');
$payload = json_encode($payload);
// Handle some overzealous escaping in PHP json that seemed to cause some errors
// with claimsets.
$payload = str_replace('\/', '/', $payload);
$segments = array(
Google_Utils::urlSafeB64Encode(json_encode($header)),
Google_Utils::urlSafeB64Encode(json_encode($payload))
Google_Utils::urlSafeB64Encode($payload)
);
$signingInput = implode('.', $segments);
$signer = new Google_P12Signer($this->privateKey, $this->privateKeyPassword);
$signer = new Google_Signer_P12($this->privateKey, $this->privateKeyPassword);
$signature = $signer->sign($signingInput);
$segments[] = Google_Utils::urlSafeB64Encode($signature);
......
<?php
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "Google/Exception.php";
class Google_Auth_Exception extends Google_Exception
{
}
......@@ -15,13 +15,16 @@
* limitations under the License.
*/
require_once "Google/Auth/Exception.php";
/**
* Class to hold information about an authenticated login.
*
* @author Brian Eaton <beaton@google.com>
*/
class Google_LoginTicket {
const USER_ATTR = "id";
class Google_Auth_LoginTicket
{
const USER_ATTR = "sub";
// Information from id token envelope.
private $envelope;
......@@ -35,21 +38,23 @@ class Google_LoginTicket {
* @param string $envelope Header from a verified authentication token.
* @param string $payload Information from a verified authentication token.
*/
public function __construct($envelope, $payload) {
public function __construct($envelope, $payload)
{
$this->envelope = $envelope;
$this->payload = $payload;
}
/**
* Returns the numeric identifier for the user.
* @throws Google_AuthException
* @throws Google_Auth_Exception
* @return
*/
public function getUserId() {
public function getUserId()
{
if (array_key_exists(self::USER_ATTR, $this->payload)) {
return $this->payload[self::USER_ATTR];
}
throw new Google_AuthException("No user_id in token");
throw new Google_Auth_Exception("No user_id in token");
}
/**
......@@ -57,7 +62,8 @@ class Google_LoginTicket {
* various information about the user session.
* @return array
*/
public function getAttributes() {
public function getAttributes()
{
return array("envelope" => $this->envelope, "payload" => $this->payload);
}
}
......@@ -15,33 +15,47 @@
* limitations under the License.
*/
require_once "Google/Auth/Abstract.php";
require_once "Google/Http/Request.php";
/**
* Do-nothing authentication implementation, use this if you want to make un-authenticated calls
* Simple API access implementation. Can either be used to make requests
* completely unauthenticated, or by using a Simple API Access developer
* key.
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*/
class Google_AuthNone extends Google_Auth {
public $key = null;
class Google_Auth_Simple extends Google_Auth_Abstract
{
private $key = null;
private $client;
public function __construct() {
global $apiConfig;
if (!empty($apiConfig['developer_key'])) {
$this->setDeveloperKey($apiConfig['developer_key']);
}
public function __construct(Google_Client $client, $config = null)
{
$this->client = $client;
}
public function setDeveloperKey($key) {$this->key = $key;}
public function authenticate($service) {/*noop*/}
public function setAccessToken($accessToken) {/* noop*/}
public function getAccessToken() {return null;}
public function createAuthUrl($scope) {return null;}
public function refreshToken($refreshToken) {/* noop*/}
public function revokeToken() {/* noop*/}
/**
* Perform an authenticated / signed apiHttpRequest.
* This function takes the apiHttpRequest, calls apiAuth->sign on it
* (which can modify the request in what ever way fits the auth mechanism)
* and then calls apiCurlIO::makeRequest on the signed request
*
* @param Google_Http_Request $request
* @return Google_Http_Request The resulting HTTP response including the
* responseHttpCode, responseHeaders and responseBody.
*/
public function authenticatedRequest(Google_Http_Request $request)
{
$request = $this->sign($request);
return $this->io->makeRequest($request);
}
public function sign(Google_HttpRequest $request) {
if ($this->key) {
$request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&')
. 'key='.urlencode($this->key));
public function sign(Google_Http_Request $request)
{
$key = $this->client->getClassConfig($this, 'developer_key');
if ($key) {
$request->setQueryParam('key', $key);
}
return $request;
}
......
......@@ -15,15 +15,15 @@
* limitations under the License.
*/
require_once "Google_FileCache.php";
require_once "Google_MemcacheCache.php";
/**
* Abstract storage class
*
* @author Chris Chabot <chabotc@google.com>
*/
abstract class Google_Cache {
abstract class Google_Cache_Abstract
{
abstract public function __construct(Google_Client $client);
/**
* Retrieves the data for the given key, or false if they
......@@ -33,7 +33,7 @@ abstract class Google_Cache {
* @param boolean|int $expiration Expiration time in seconds
*
*/
abstract function get($key, $expiration = false);
abstract public function get($key, $expiration = false);
/**
* Store the key => $value set. The $value is serialized
......@@ -42,14 +42,12 @@ abstract class Google_Cache {
* @param string $key Key of the data
* @param string $value data
*/
abstract function set($key, $value);
abstract public function set($key, $value);
/**
* Removes the key/data pair for the given $key
*
* @param String $key
*/
abstract function delete($key);
abstract public function delete($key);
}
......@@ -14,77 +14,51 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "Google/Cache/Abstract.php";
require_once "Google/Cache/Exception.php";
/**
* A persistent storage class based on the APC cache, which is not
* really very persistent, as soon as you restart your web server
* the storage will be wiped, however for debugging and/or speed
* it can be useful, kinda, and cache is a lot cheaper then storage.
* it can be useful, and cache is a lot cheaper then storage.
*
* @author Chris Chabot <chabotc@google.com>
*/
class googleApcCache extends Google_Cache {
public function __construct() {
if (! function_exists('apc_add')) {
throw new Google_CacheException("Apc functions not available");
}
}
private function isLocked($key) {
if ((@apc_fetch($key . '.lock')) === false) {
return false;
}
return true;
}
private function createLock($key) {
// the interesting thing is that this could fail if the lock was created in the meantime..
// but we'll ignore that out of convenience
@apc_add($key . '.lock', '', 5);
}
private function removeLock($key) {
// suppress all warnings, if some other process removed it that's ok too
@apc_delete($key . '.lock');
}
private function waitForLock($key) {
// 20 x 250 = 5 seconds
$tries = 20;
$cnt = 0;
do {
// 250 ms is a long time to sleep, but it does stop the server from burning all resources on polling locks..
usleep(250);
$cnt ++;
} while ($cnt <= $tries && $this->isLocked($key));
if ($this->isLocked($key)) {
// 5 seconds passed, assume the owning process died off and remove it
$this->removeLock($key);
class Google_Cache_Apc extends Google_Cache_Abstract
{
public function __construct(Google_Client $client)
{
if (! function_exists('apc_add') ) {
throw new Google_Cache_Exception("Apc functions not available");
}
}
/**
* @inheritDoc
*/
public function get($key, $expiration = false) {
if (($ret = @apc_fetch($key)) === false) {
public function get($key, $expiration = false)
{
$ret = apc_fetch($key);
if ($ret === false) {
return false;
}
if (!$expiration || (time() - $ret['time'] > $expiration)) {
if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
$this->delete($key);
return false;
}
return unserialize($ret['data']);
return $ret['data'];
}
/**
* @inheritDoc
*/
public function set($key, $value) {
if (@apc_store($key, array('time' => time(), 'data' => serialize($value))) == false) {
throw new Google_CacheException("Couldn't store data");
public function set($key, $value)
{
$rc = apc_store($key, array('time' => time(), 'data' => $value));
if ($rc == false) {
throw new Google_Cache_Exception("Couldn't store data");
}
}
......@@ -92,7 +66,8 @@ class googleApcCache extends Google_Cache {
* @inheritDoc
* @param String $key
*/
public function delete($key) {
@apc_delete($key);
public function delete($key)
{
apc_delete($key);
}
}
<?php
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software