Commit 73442dbf authored by Ad Schellevis's avatar Ad Schellevis

sync master

parent 5dfd99a5
<?php
/**
* Copyright (C) 2015 Deciso B.V.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace Google\API;
class Drive
{
/**
* @var null|\Google_Service_Drive service pointer
*/
private $service = null;
/**
* @var null|\Google_Client pointer to client
*/
private $client = null;
public function __construct()
{
// hook in Google's autoloader
require_once(__DIR__."/src/Google/autoload.php");
}
/**
* login to google drive
* @param $client_id
* @param $privateKeyB64 P12 key placed in a base64 container
*/
public function login($client_id, $privateKeyB64)
{
$this->client = new \Google_Client();
$key = base64_decode($privateKeyB64);
$cred = new \Google_Auth_AssertionCredentials(
$client_id,
array('https://www.googleapis.com/auth/drive'),
$key
);
$this->client->setAssertionCredentials($cred);
$this->service = new \Google_Service_Drive($this->client);
}
/**
* retrieve directory listing
* @param $directoryId parent directory id
* @param $filename title/filename of object
* @return mixed list of files
*/
public function listFiles($directoryId, $filename = null)
{
$query = "'".$directoryId."' in parents ";
if ($filename != null) {
$query .= " and title in '".$filename."'";
}
return $this->service->files->listFiles(array('q' => $query));
}
/**
* @param $fileHandle (object from listFiles)
* @return null|string
*/
public function download($fileHandle)
{
$sUrl = $fileHandle->getDownloadUrl();
$request = new \Google_Http_Request($sUrl, 'GET', null, null);
$httpRequest = $this->client->getAuth()->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// Error, no content fetched
return null;
}
}
/**
* Upload file
* @param string $directoryId (parent id)
* @param string $filename
* @param string $content
* @param string $mimetype
* @return handle
*/
public function upload($directoryId, $filename, $content, $mimetype = 'text/plain')
{
$parent = new \Google_Service_Drive_ParentReference();
$parent->setId($directoryId);
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($filename);
$file->setDescription($filename);
$file->setMimeType('text/plain');
$file->setParents(array($parent));
$createdFile = $this->service->files->insert($file, array(
'data' => $content,
'mimeType' => $mimetype,
'uploadType' => 'media',
));
return $createdFile;
}
/**
* delete file
* @param $fileHandle (object from listFiles)
*/
public function delete($fileHandle)
{
$this->service->files->delete($fileHandle['id']);
}
}
\ No newline at end of file
<?php
/*
* Copyright 2010 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Abstract class for the Authentication in the API client
* @author Chris Chabot <chabotc@google.com>
*
*/
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);
}
<?php
/*
* Copyright 2014 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.
*/
/*
* WARNING - this class depends on the Google App Engine PHP library
* which is 5.3 and above only, so if you include this in a PHP 5.2
* setup or one without 5.3 things will blow up.
*/
use google\appengine\api\app_identity\AppIdentityService;
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Authentication via the Google App Engine App Identity service.
*/
class Google_Auth_AppIdentity extends Google_Auth_Abstract
{
const CACHE_PREFIX = "Google_Auth_AppIdentity::";
private $key = null;
private $client;
private $token = false;
private $tokenScopes = false;
public function __construct(Google_Client $client, $config = null)
{
$this->client = $client;
}
/**
* Retrieve an access token for the scopes supplied.
*/
public function authenticateForScope($scopes)
{
if ($this->token && $this->tokenScopes == $scopes) {
return $this->token;
}
$cacheKey = self::CACHE_PREFIX;
if (is_string($scopes)) {
$cacheKey .= $scopes;
} else if (is_array($scopes)) {
$cacheKey .= implode(":", $scopes);
}
$this->token = $this->client->getCache()->get($cacheKey);
if (!$this->token) {
$this->retrieveToken($scopes, $cacheKey);
} else if ($this->token['expiration_time'] < time()) {
$this->client->getCache()->delete($cacheKey);
$this->retrieveToken($scopes, $cacheKey);
}
$this->tokenScopes = $scopes;
return $this->token;
}
/**
* Retrieve a new access token and store it in cache
* @param mixed $scopes
* @param string $cacheKey
*/
private function retrieveToken($scopes, $cacheKey)
{
$this->token = AppIdentityService::getAccessToken($scopes);
if ($this->token) {
$this->client->getCache()->set(
$cacheKey,
$this->token
);
}
}
/**
* 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->client->getIo()->makeRequest($request);
}
public function sign(Google_Http_Request $request)
{
if (!$this->token) {
// No token, so nothing to do.
return $request;
}
$this->client->getLogger()->debug('App Identity authentication');
// Add the OAuth2 header to the request
$request->setRequestHeaders(
array('Authorization' => 'Bearer ' . $this->token['access_token'])
);
return $request;
}
}
<?php
/*
* Copyright 2012 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Credentials object used for OAuth 2.0 Signed JWT assertion grants.
*/
class Google_Auth_AssertionCredentials
{
const MAX_TOKEN_LIFETIME_SECS = 3600;
public $serviceAccountName;
public $scopes;
public $privateKey;
public $privateKeyPassword;
public $assertionType;
public $sub;
/**
* @deprecated
* @link http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
*/
public $prn;
private $useCache;
/**
* @param $serviceAccountName
* @param $scopes array List of scopes
* @param $privateKey
* @param string $privateKeyPassword
* @param string $assertionType
* @param bool|string $sub The email address of the user for which the
* 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,
$scopes,
$privateKey,
$privateKeyPassword = 'notasecret',
$assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
$sub = false,
$useCache = true
) {
$this->serviceAccountName = $serviceAccountName;
$this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
$this->privateKey = $privateKey;
$this->privateKeyPassword = $privateKeyPassword;
$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()
{
$now = time();
$jwtParams = array(
'aud' => Google_Auth_OAuth2::OAUTH2_TOKEN_URI,
'scope' => $this->scopes,
'iat' => $now,
'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
'iss' => $this->serviceAccountName,
);
if ($this->sub !== false) {
$jwtParams['sub'] = $this->sub;
} else if ($this->prn !== false) {
$jwtParams['prn'] = $this->prn;
}
return $this->makeSignedJwt($jwtParams);
}
/**
* Creates a signed JWT.
* @param array $payload
* @return string The signed JWT.
*/
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($payload)
);
$signingInput = implode('.', $segments);
$signer = new Google_Signer_P12($this->privateKey, $this->privateKeyPassword);
$signature = $signer->sign($signingInput);
$segments[] = Google_Utils::urlSafeB64Encode($signature);
return implode(".", $segments);
}
}
<?php
/*
* Copyright 2014 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Authentication via built-in Compute Engine service accounts.
* The instance must be pre-configured with a service account
* and the appropriate scopes.
* @author Jonathan Parrott <jon.wayne.parrott@gmail.com>
*/
class Google_Auth_ComputeEngine extends Google_Auth_Abstract
{
const METADATA_AUTH_URL =
'http://metadata/computeMetadata/v1/instance/service-accounts/default/token';
private $client;
private $token;
public function __construct(Google_Client $client, $config = null)
{
$this->client = $client;
}
/**
* 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->client->getIo()->makeRequest($request);
}
/**
* @param string $token
* @throws Google_Auth_Exception
*/
public function setAccessToken($token)
{
$token = json_decode($token, true);
if ($token == null) {
throw new Google_Auth_Exception('Could not json decode the token');
}
if (! isset($token['access_token'])) {
throw new Google_Auth_Exception("Invalid token format");
}
$token['created'] = time();
$this->token = $token;
}
public function getAccessToken()
{
return json_encode($this->token);
}
/**
* Acquires a new access token from the compute engine metadata server.
* @throws Google_Auth_Exception
*/
public function acquireAccessToken()
{
$request = new Google_Http_Request(
self::METADATA_AUTH_URL,
'GET',
array(
'Metadata-Flavor' => 'Google'
)
);
$request->disableGzip();
$response = $this->client->getIo()->makeRequest($request);
if ($response->getResponseHttpCode() == 200) {
$this->setAccessToken($response->getResponseBody());
$this->token['created'] = time();
return $this->getAccessToken();
} else {
throw new Google_Auth_Exception(
sprintf(
"Error fetching service account access token, message: '%s'",
$response->getResponseBody()
),
$response->getResponseHttpCode()
);
}
}
/**
* Include an accessToken in a given apiHttpRequest.
* @param Google_Http_Request $request
* @return Google_Http_Request
* @throws Google_Auth_Exception
*/
public function sign(Google_Http_Request $request)
{
if ($this->isAccessTokenExpired()) {
$this->acquireAccessToken();
}
$this->client->getLogger()->debug('Compute engine service account authentication');
$request->setRequestHeaders(
array('Authorization' => 'Bearer ' . $this->token['access_token'])
);
return $request;
}
/**
* Returns if the access_token is expired.
* @return bool Returns True if the access_token is expired.
*/
public function isAccessTokenExpired()
{
if (!$this->token || !isset($this->token['created'])) {
return true;
}
// If the token is set to expire in the next 30 seconds.
$expired = ($this->token['created']
+ ($this->token['expires_in'] - 30)) < time();
return $expired;
}
}
<?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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
class Google_Auth_Exception extends Google_Exception
{
}
<?php
/*
* Copyright 2011 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Class to hold information about an authenticated login.
*
* @author Brian Eaton <beaton@google.com>
*/
class Google_Auth_LoginTicket
{
const USER_ATTR = "sub";
// Information from id token envelope.
private $envelope;
// Information from id token payload.
private $payload;
/**
* Creates a user based on the supplied token.
*
* @param string $envelope Header from a verified authentication token.
* @param string $payload Information from a verified authentication token.
*/
public function __construct($envelope, $payload)
{
$this->envelope = $envelope;
$this->payload = $payload;
}
/**
* Returns the numeric identifier for the user.
* @throws Google_Auth_Exception
* @return
*/
public function getUserId()
{
if (array_key_exists(self::USER_ATTR, $this->payload)) {
return $this->payload[self::USER_ATTR];
}
throw new Google_Auth_Exception("No user_id in token");
}
/**
* Returns attributes from the login ticket. This can contain
* various information about the user session.
* @return array
*/
public function getAttributes()
{
return array("envelope" => $this->envelope, "payload" => $this->payload);
}
}
<?php
/*
* Copyright 2010 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Simple API access implementation. Can either be used to make requests
* completely unauthenticated, or by using a Simple API Access developer
* key.
*/
class Google_Auth_Simple extends Google_Auth_Abstract
{
private $key = null;
private $client;
public function __construct(Google_Client $client, $config = null)
{
$this->client = $client;
}
/**
* 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_Http_Request $request)
{
$key = $this->client->getClassConfig($this, 'developer_key');
if ($key) {
$this->client->getLogger()->debug(
'Simple API Access developer key authentication'
);
$request->setQueryParam('key', $key);
}
return $request;
}
}
<?php
/*
* Copyright 2008 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.
*/
/**
* Abstract storage class
*
* @author Chris Chabot <chabotc@google.com>
*/
abstract class Google_Cache_Abstract
{
abstract public function __construct(Google_Client $client);
/**
* Retrieves the data for the given key, or false if they
* key is unknown or expired
*
* @param String $key The key who's data to retrieve
* @param boolean|int $expiration Expiration time in seconds
*
*/
abstract public function get($key, $expiration = false);
/**
* Store the key => $value set. The $value is serialized
* by this function so can be of any type
*
* @param string $key Key of the data
* @param string $value data
*/
abstract public function set($key, $value);
/**
* Removes the key/data pair for the given $key
*
* @param String $key
*/
abstract public function delete($key);
}
<?php
/*
* Copyright 2010 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.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, and cache is a lot cheaper then storage.
*
* @author Chris Chabot <chabotc@google.com>
*/
class Google_Cache_Apc extends Google_Cache_Abstract
{
/**
* @var Google_Client the current client
*/
private $client;
public function __construct(Google_Client $client)
{
if (! function_exists('apc_add') ) {
$error = "Apc functions not available";
$client->getLogger()->error($error);
throw new Google_Cache_Exception($error);
}
$this->client = $client;
}
/**
* @inheritDoc
*/
public function get($key, $expiration = false)
{
$ret = apc_fetch($key);
if ($ret === false) {
$this->client->getLogger()->debug(
'APC cache miss',
array('key' => $key)
);
return false;
}
if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
$this->client->getLogger()->debug(
'APC cache miss (expired)',
array('key' => $key, 'var' => $ret)
);
$this->delete($key);
return false;
}
$this->client->getLogger()->debug(
'APC cache hit',
array('key' => $key, 'var' => $ret)
);
return $ret['data'];
}
/**
* @inheritDoc
*/
public function set($key, $value)
{
$var = array('time' => time(), 'data' => $value);
$rc = apc_store($key, $var);
if ($rc == false) {
$this->client->getLogger()->error(
'APC cache set failed',
array('key' => $key, 'var' => $var)
);
throw new Google_Cache_Exception("Couldn't store data");
}
$this->client->getLogger()->debug(
'APC cache set',
array('key' => $key, 'var' => $var)
);
}
/**
* @inheritDoc
* @param String $key
*/
public function delete($key)
{
$this->client->getLogger()->debug(
'APC cache delete',
array('key' => $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
* 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
class Google_Cache_Exception extends Google_Exception
{
}
<?php
/*
* Copyright 2008 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/*
* This class implements a basic on disk storage. While that does
* work quite well it's not the most elegant and scalable solution.
* It will also get you into a heap of trouble when you try to run
* this in a clustered environment.
*
* @author Chris Chabot <chabotc@google.com>
*/
class Google_Cache_File extends Google_Cache_Abstract
{
const MAX_LOCK_RETRIES = 10;
private $path;
private $fh;
/**
* @var Google_Client the current client
*/
private $client;
public function __construct(Google_Client $client)
{
$this->client = $client;
$this->path = $this->client->getClassConfig($this, 'directory');
}
public function get($key, $expiration = false)
{
$storageFile = $this->getCacheFile($key);
$data = false;
if (!file_exists($storageFile)) {
$this->client->getLogger()->debug(
'File cache miss',
array('key' => $key, 'file' => $storageFile)
);
return false;
}
if ($expiration) {
$mtime = filemtime($storageFile);
if ((time() - $mtime) >= $expiration) {
$this->client->getLogger()->debug(
'File cache miss (expired)',
array('key' => $key, 'file' => $storageFile)
);
$this->delete($key);
return false;
}
}
if ($this->acquireReadLock($storageFile)) {
if (filesize($storageFile) > 0) {
$data = fread($this->fh, filesize($storageFile));
$data = unserialize($data);
} else {
$this->client->getLogger()->debug(
'Cache file was empty',
array('file' => $storageFile)
);
}
$this->unlock($storageFile);
}
$this->client->getLogger()->debug(
'File cache hit',
array('key' => $key, 'file' => $storageFile, 'var' => $data)
);
return $data;
}
public function set($key, $value)
{
$storageFile = $this->getWriteableCacheFile($key);
if ($this->acquireWriteLock($storageFile)) {
// We serialize the whole request object, since we don't only want the
// responseContent but also the postBody used, headers, size, etc.
$data = serialize($value);
$result = fwrite($this->fh, $data);
$this->unlock($storageFile);
$this->client->getLogger()->debug(
'File cache set',
array('key' => $key, 'file' => $storageFile, 'var' => $value)
);
} else {
$this->client->getLogger()->notice(
'File cache set failed',
array('key' => $key, 'file' => $storageFile)
);
}
}
public function delete($key)
{
$file = $this->getCacheFile($key);
if (file_exists($file) && !unlink($file)) {
$this->client->getLogger()->error(
'File cache delete failed',
array('key' => $key, 'file' => $file)
);
throw new Google_Cache_Exception("Cache file could not be deleted");
}
$this->client->getLogger()->debug(
'File cache delete',
array('key' => $key, 'file' => $file)
);
}
private function getWriteableCacheFile($file)
{
return $this->getCacheFile($file, true);
}
private function getCacheFile($file, $forWrite = false)
{
return $this->getCacheDir($file, $forWrite) . '/' . md5($file);
}
private function getCacheDir($file, $forWrite)
{
// use the first 2 characters of the hash as a directory prefix
// this should prevent slowdowns due to huge directory listings
// and thus give some basic amount of scalability
$storageDir = $this->path . '/' . substr(md5($file), 0, 2);
if ($forWrite && ! is_dir($storageDir)) {
if (! mkdir($storageDir, 0755, true)) {
$this->client->getLogger()->error(
'File cache creation failed',
array('dir' => $storageDir)
);
throw new Google_Cache_Exception("Could not create storage directory: $storageDir");
}
}
return $storageDir;
}
private function acquireReadLock($storageFile)
{
return $this->acquireLock(LOCK_SH, $storageFile);
}
private function acquireWriteLock($storageFile)
{
$rc = $this->acquireLock(LOCK_EX, $storageFile);
if (!$rc) {
$this->client->getLogger()->notice(
'File cache write lock failed',
array('file' => $storageFile)
);
$this->delete($storageFile);
}
return $rc;
}
private function acquireLock($type, $storageFile)
{
$mode = $type == LOCK_EX ? "w" : "r";
$this->fh = fopen($storageFile, $mode);
if (!$this->fh) {
$this->client->getLogger()->error(
'Failed to open file during lock acquisition',
array('file' => $storageFile)
);
return false;
}
$count = 0;
while (!flock($this->fh, $type | LOCK_NB)) {
// Sleep for 10ms.
usleep(10000);
if (++$count < self::MAX_LOCK_RETRIES) {
return false;
}
}
return true;
}
public function unlock($storageFile)
{
if ($this->fh) {
flock($this->fh, LOCK_UN);
}
}
}
<?php
/*
* Copyright 2008 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* A persistent storage class based on the memcache, which is not
* really very persistent, as soon as you restart your memcache daemon
* the storage will be wiped.
*
* Will use either the memcache or memcached extensions, preferring
* memcached.
*
* @author Chris Chabot <chabotc@google.com>
*/
class Google_Cache_Memcache extends Google_Cache_Abstract
{
private $connection = false;
private $mc = false;
private $host;
private $port;
/**
* @var Google_Client the current client
*/
private $client;
public function __construct(Google_Client $client)
{
if (!function_exists('memcache_connect') && !class_exists("Memcached")) {
$error = "Memcache functions not available";
$client->getLogger()->error($error);
throw new Google_Cache_Exception($error);
}
$this->client = $client;
if ($client->isAppEngine()) {
// No credentials needed for GAE.
$this->mc = new Memcached();
$this->connection = true;
} else {
$this->host = $client->getClassConfig($this, 'host');
$this->port = $client->getClassConfig($this, 'port');
if (empty($this->host) || (empty($this->port) && (string) $this->port != "0")) {
$error = "You need to supply a valid memcache host and port";
$client->getLogger()->error($error);
throw new Google_Cache_Exception($error);
}
}
}
/**
* @inheritDoc
*/
public function get($key, $expiration = false)
{
$this->connect();
$ret = false;
if ($this->mc) {
$ret = $this->mc->get($key);
} else {
$ret = memcache_get($this->connection, $key);
}
if ($ret === false) {
$this->client->getLogger()->debug(
'Memcache cache miss',
array('key' => $key)
);
return false;
}
if (is_numeric($expiration) && (time() - $ret['time'] > $expiration)) {
$this->client->getLogger()->debug(
'Memcache cache miss (expired)',
array('key' => $key, 'var' => $ret)
);
$this->delete($key);
return false;
}
$this->client->getLogger()->debug(
'Memcache cache hit',
array('key' => $key, 'var' => $ret)
);
return $ret['data'];
}
/**
* @inheritDoc
* @param string $key
* @param string $value
* @throws Google_Cache_Exception
*/
public function set($key, $value)
{
$this->connect();
// we store it with the cache_time default expiration so objects will at
// least get cleaned eventually.
$data = array('time' => time(), 'data' => $value);
$rc = false;
if ($this->mc) {
$rc = $this->mc->set($key, $data);
} else {
$rc = memcache_set($this->connection, $key, $data, false);
}
if ($rc == false) {
$this->client->getLogger()->error(
'Memcache cache set failed',
array('key' => $key, 'var' => $data)
);
throw new Google_Cache_Exception("Couldn't store data in cache");
}
$this->client->getLogger()->debug(
'Memcache cache set',
array('key' => $key, 'var' => $data)
);
}
/**
* @inheritDoc
* @param String $key
*/
public function delete($key)
{
$this->connect();
if ($this->mc) {
$this->mc->delete($key, 0);
} else {
memcache_delete($this->connection, $key, 0);
}
$this->client->getLogger()->debug(
'Memcache cache delete',
array('key' => $key)
);
}
/**
* Lazy initialiser for memcache connection. Uses pconnect for to take
* advantage of the persistence pool where possible.
*/
private function connect()
{
if ($this->connection) {
return;
}
if (class_exists("Memcached")) {
$this->mc = new Memcached();
$this->mc->addServer($this->host, $this->port);
$this->connection = true;
} else {
$this->connection = memcache_pconnect($this->host, $this->port);
}
if (! $this->connection) {
$error = "Couldn't connect to memcache server";
$this->client->getLogger()->error($error);
throw new Google_Cache_Exception($error);
}
}
}
<?php
/*
* Copyright 2014 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* A blank storage class, for cases where caching is not
* required.
*/
class Google_Cache_Null extends Google_Cache_Abstract
{
public function __construct(Google_Client $client)
{
}
/**
* @inheritDoc
*/
public function get($key, $expiration = false)
{
return false;
}
/**
* @inheritDoc
*/
public function set($key, $value)
{
// Nop.
}
/**
* @inheritDoc
* @param String $key
*/
public function delete($key)
{
// Nop.
}
}
This diff is collapsed.
<?php
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Extension to the regular Google_Model that automatically
* exposes the items array for iteration, so you can just
* iterate over the object rather than a reference inside.
*/
class Google_Collection extends Google_Model implements Iterator, Countable
{
protected $collection_key = 'items';
public function rewind()
{
if (isset($this->modelData[$this->collection_key])
&& is_array($this->modelData[$this->collection_key])) {
reset($this->modelData[$this->collection_key]);
}
}
public function current()
{
$this->coerceType($this->key());
if (is_array($this->modelData[$this->collection_key])) {
return current($this->modelData[$this->collection_key]);
}
}
public function key()
{
if (isset($this->modelData[$this->collection_key])
&& is_array($this->modelData[$this->collection_key])) {
return key($this->modelData[$this->collection_key]);
}
}
public function next()
{
return next($this->modelData[$this->collection_key]);
}
public function valid()
{
$key = $this->key();
return $key !== null && $key !== false;
}
public function count()
{
if (!isset($this->modelData[$this->collection_key])) {
return 0;
}
return count($this->modelData[$this->collection_key]);
}
public function offsetExists ($offset)
{
if (!is_numeric($offset)) {
return parent::offsetExists($offset);
}
return isset($this->modelData[$this->collection_key][$offset]);
}
public function offsetGet($offset)
{
if (!is_numeric($offset)) {
return parent::offsetGet($offset);
}
$this->coerceType($offset);
return $this->modelData[$this->collection_key][$offset];
}
public function offsetSet($offset, $value)
{
if (!is_numeric($offset)) {
return parent::offsetSet($offset, $value);
}
$this->modelData[$this->collection_key][$offset] = $value;
}
public function offsetUnset($offset)
{
if (!is_numeric($offset)) {
return parent::offsetUnset($offset);
}
unset($this->modelData[$this->collection_key][$offset]);
}
private function coerceType($offset)
{
$typeKey = $this->keyType($this->collection_key);
if (isset($this->$typeKey) && !is_object($this->modelData[$this->collection_key][$offset])) {
$type = $this->$typeKey;
$this->modelData[$this->collection_key][$offset] =
new $type($this->modelData[$this->collection_key][$offset]);
}
}
}
This diff is collapsed.
<?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.
*/
class Google_Exception extends Exception
{
}
<?php
/*
* Copyright 2012 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Class to handle batched requests to the Google API service.
*/
class Google_Http_Batch
{
/** @var string Multipart Boundary. */
private $boundary;
/** @var array service requests to be executed. */
private $requests = array();
/** @var Google_Client */
private $client;
private $expected_classes = array();
private $base_path;
public function __construct(Google_Client $client, $boundary = false)
{
$this->client = $client;
$this->base_path = $this->client->getBasePath();
$this->expected_classes = array();
$boundary = (false == $boundary) ? mt_rand() : $boundary;
$this->boundary = str_replace('"', '', $boundary);
}
public function add(Google_Http_Request $request, $key = false)
{
if (false == $key) {
$key = mt_rand();
}
$this->requests[$key] = $request;
}
public function execute()
{
$body = '';
/** @var Google_Http_Request $req */
foreach ($this->requests as $key => $req) {
$body .= "--{$this->boundary}\n";
$body .= $req->toBatchString($key) . "\n";
$this->expected_classes["response-" . $key] = $req->getExpectedClass();
}
$body = rtrim($body);
$body .= "\n--{$this->boundary}--";
$url = $this->base_path . '/batch';
$httpRequest = new Google_Http_Request($url, 'POST');
$httpRequest->setRequestHeaders(
array('Content-Type' => 'multipart/mixed; boundary=' . $this->boundary)
);
$httpRequest->setPostBody($body);
$response = $this->client->getIo()->makeRequest($httpRequest);
return $this->parseResponse($response);
}
public function parseResponse(Google_Http_Request $response)
{
$contentType = $response->getResponseHeader('content-type');
$contentType = explode(';', $contentType);
$boundary = false;
foreach ($contentType as $part) {
$part = (explode('=', $part, 2));
if (isset($part[0]) && 'boundary' == trim($part[0])) {
$boundary = $part[1];
}
}
$body = $response->getResponseBody();
if ($body) {
$body = str_replace("--$boundary--", "--$boundary", $body);
$parts = explode("--$boundary", $body);
$responses = array();
foreach ($parts as $part) {
$part = trim($part);
if (!empty($part)) {
list($metaHeaders, $part) = explode("\r\n\r\n", $part, 2);
$metaHeaders = $this->client->getIo()->getHttpResponseHeaders($metaHeaders);
$status = substr($part, 0, strpos($part, "\n"));
$status = explode(" ", $status);
$status = $status[1];
list($partHeaders, $partBody) = $this->client->getIo()->ParseHttpResponse($part, false);
$response = new Google_Http_Request("");
$response->setResponseHttpCode($status);
$response->setResponseHeaders($partHeaders);
$response->setResponseBody($partBody);
// Need content id.
$key = $metaHeaders['content-id'];
if (isset($this->expected_classes[$key]) &&
strlen($this->expected_classes[$key]) > 0) {
$class = $this->expected_classes[$key];
$response->setExpectedClass($class);
}
try {
$response = Google_Http_REST::decodeHttpResponse($response, $this->client);
$responses[$key] = $response;
} catch (Google_Service_Exception $e) {
// Store the exception as the response, so successful responses
// can be processed.
$responses[$key] = $e;
}
}
}
return $responses;
}
return null;
}
}
<?php
/*
* Copyright 2012 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Implement the caching directives specified in rfc2616. This
* implementation is guided by the guidance offered in rfc2616-sec13.
*/
class Google_Http_CacheParser
{
public static $CACHEABLE_HTTP_METHODS = array('GET', 'HEAD');
public static $CACHEABLE_STATUS_CODES = array('200', '203', '300', '301');
/**
* Check if an HTTP request can be cached by a private local cache.
*
* @static
* @param Google_Http_Request $resp
* @return bool True if the request is cacheable.
* False if the request is uncacheable.
*/
public static function isRequestCacheable(Google_Http_Request $resp)
{
$method = $resp->getRequestMethod();
if (! in_array($method, self::$CACHEABLE_HTTP_METHODS)) {
return false;
}
// Don't cache authorized requests/responses.
// [rfc2616-14.8] When a shared cache receives a request containing an
// Authorization field, it MUST NOT return the corresponding response
// as a reply to any other request...
if ($resp->getRequestHeader("authorization")) {
return false;
}
return true;
}
/**
* Check if an HTTP response can be cached by a private local cache.
*
* @static
* @param Google_Http_Request $resp
* @return bool True if the response is cacheable.
* False if the response is un-cacheable.
*/
public static function isResponseCacheable(Google_Http_Request $resp)
{
// First, check if the HTTP request was cacheable before inspecting the
// HTTP response.
if (false == self::isRequestCacheable($resp)) {
return false;
}
$code = $resp->getResponseHttpCode();
if (! in_array($code, self::$CACHEABLE_STATUS_CODES)) {
return false;
}
// The resource is uncacheable if the resource is already expired and
// the resource doesn't have an ETag for revalidation.
$etag = $resp->getResponseHeader("etag");
if (self::isExpired($resp) && $etag == false) {
return false;
}
// [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
// store any part of either this response or the request that elicited it.
$cacheControl = $resp->getParsedCacheControl();
if (isset($cacheControl['no-store'])) {
return false;
}
// Pragma: no-cache is an http request directive, but is occasionally
// used as a response header incorrectly.
$pragma = $resp->getResponseHeader('pragma');
if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
return false;
}
// [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
// a cache cannot determine from the request headers of a subsequent request
// whether this response is the appropriate representation."
// Given this, we deem responses with the Vary header as uncacheable.
$vary = $resp->getResponseHeader('vary');
if ($vary) {
return false;
}
return true;
}
/**
* @static
* @param Google_Http_Request $resp
* @return bool True if the HTTP response is considered to be expired.
* False if it is considered to be fresh.
*/
public static function isExpired(Google_Http_Request $resp)
{
// HTTP/1.1 clients and caches MUST treat other invalid date formats,
// especially including the value “0”, as in the past.
$parsedExpires = false;
$responseHeaders = $resp->getResponseHeaders();
if (isset($responseHeaders['expires'])) {
$rawExpires = $responseHeaders['expires'];
// Check for a malformed expires header first.
if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
return true;
}
// See if we can parse the expires header.
$parsedExpires = strtotime($rawExpires);
if (false == $parsedExpires || $parsedExpires <= 0) {
return true;
}
}
// Calculate the freshness of an http response.
$freshnessLifetime = false;
$cacheControl = $resp->getParsedCacheControl();
if (isset($cacheControl['max-age'])) {
$freshnessLifetime = $cacheControl['max-age'];
}
$rawDate = $resp->getResponseHeader('date');
$parsedDate = strtotime($rawDate);
if (empty($rawDate) || false == $parsedDate) {
// We can't default this to now, as that means future cache reads
// will always pass with the logic below, so we will require a
// date be injected if not supplied.
throw new Google_Exception("All cacheable requests must have creation dates.");
}
if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
$freshnessLifetime = $parsedExpires - $parsedDate;
}
if (false == $freshnessLifetime) {
return true;
}
// Calculate the age of an http response.
$age = max(0, time() - $parsedDate);
if (isset($responseHeaders['age'])) {
$age = max($age, strtotime($responseHeaders['age']));
}
return $freshnessLifetime <= $age;
}
/**
* Determine if a cache entry should be revalidated with by the origin.
*
* @param Google_Http_Request $response
* @return bool True if the entry is expired, else return false.
*/
public static function mustRevalidate(Google_Http_Request $response)
{
// [13.3] When a cache has a stale entry that it would like to use as a
// response to a client's request, it first has to check with the origin
// server to see if its cached entry is still usable.
return self::isExpired($response);
}
}
<?php
/**
* Copyright 2012 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* Manage large file uploads, which may be media but can be any type
* of sizable data.
*/
class Google_Http_MediaFileUpload
{
const UPLOAD_MEDIA_TYPE = 'media';
const UPLOAD_MULTIPART_TYPE = 'multipart';
const UPLOAD_RESUMABLE_TYPE = 'resumable';
/** @var string $mimeType */
private $mimeType;
/** @var string $data */
private $data;
/** @var bool $resumable */
private $resumable;
/** @var int $chunkSize */
private $chunkSize;
/** @var int $size */
private $size;
/** @var string $resumeUri */
private $resumeUri;
/** @var int $progress */
private $progress;
/** @var Google_Client */
private $client;
/** @var Google_Http_Request */
private $request;
/** @var string */
private $boundary;
/**
* Result code from last HTTP call
* @var int
*/
private $httpResultCode;
/**
* @param $mimeType string
* @param $data string The bytes you want to upload.
* @param $resumable bool
* @param bool $chunkSize File will be uploaded in chunks of this many bytes.
* only used if resumable=True
*/
public function __construct(
Google_Client $client,
Google_Http_Request $request,
$mimeType,
$data,
$resumable = false,
$chunkSize = false,
$boundary = false
) {
$this->client = $client;
$this->request = $request;
$this->mimeType = $mimeType;
$this->data = $data;
$this->size = strlen($this->data);
$this->resumable = $resumable;
if (!$chunkSize) {
$chunkSize = 256 * 1024;
}
$this->chunkSize = $chunkSize;
$this->progress = 0;
$this->boundary = $boundary;
// Process Media Request
$this->process();
}
/**
* Set the size of the file that is being uploaded.
* @param $size - int file size in bytes
*/
public function setFileSize($size)
{
$this->size = $size;
}
/**
* Return the progress on the upload
* @return int progress in bytes uploaded.
*/
public function getProgress()
{
return $this->progress;
}
/**
* Return the HTTP result code from the last call made.
* @return int code
*/
public function getHttpResultCode()
{
return $this->httpResultCode;
}
/**
* Send the next part of the file to upload.
* @param [$chunk] the next set of bytes to send. If false will used $data passed
* at construct time.
*/
public function nextChunk($chunk = false)
{
if (false == $this->resumeUri) {
$this->resumeUri = $this->getResumeUri();
}
if (false == $chunk) {
$chunk = substr($this->data, $this->progress, $this->chunkSize);
}
$lastBytePos = $this->progress + strlen($chunk) - 1;
$headers = array(
'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
'content-type' => $this->request->getRequestHeader('content-type'),
'content-length' => $this->chunkSize,
'expect' => '',
);
$httpRequest = new Google_Http_Request(
$this->resumeUri,
'PUT',
$headers,
$chunk
);
if ($this->client->getClassConfig("Google_Http_Request", "enable_gzip_for_uploads")) {
$httpRequest->enableGzip();
} else {
$httpRequest->disableGzip();
}
$response = $this->client->getIo()->makeRequest($httpRequest);
$response->setExpectedClass($this->request->getExpectedClass());
$code = $response->getResponseHttpCode();
$this->httpResultCode = $code;
if (308 == $code) {
// Track the amount uploaded.
$range = explode('-', $response->getResponseHeader('range'));
$this->progress = $range[1] + 1;
// Allow for changing upload URLs.
$location = $response->getResponseHeader('location');
if ($location) {
$this->resumeUri = $location;
}
// No problems, but upload not complete.
return false;
} else {
return Google_Http_REST::decodeHttpResponse($response, $this->client);
}
}
/**
* @param $meta
* @param $params
* @return array|bool
* @visible for testing
*/
private function process()
{
$postBody = false;
$contentType = false;
$meta = $this->request->getPostBody();
$meta = is_string($meta) ? json_decode($meta, true) : $meta;
$uploadType = $this->getUploadType($meta);
$this->request->setQueryParam('uploadType', $uploadType);
$this->transformToUploadUrl();
$mimeType = $this->mimeType ?
$this->mimeType :
$this->request->getRequestHeader('content-type');
if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = is_string($meta) ? $meta : json_encode($meta);
} else if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = $this->data;
} else if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
// This is a multipart/related upload.
$boundary = $this->boundary ? $this->boundary : mt_rand();
$boundary = str_replace('"', '', $boundary);
$contentType = 'multipart/related; boundary=' . $boundary;
$related = "--$boundary\r\n";
$related .= "Content-Type: application/json; charset=UTF-8\r\n";
$related .= "\r\n" . json_encode($meta) . "\r\n";
$related .= "--$boundary\r\n";
$related .= "Content-Type: $mimeType\r\n";
$related .= "Content-Transfer-Encoding: base64\r\n";
$related .= "\r\n" . base64_encode($this->data) . "\r\n";
$related .= "--$boundary--";
$postBody = $related;
}
$this->request->setPostBody($postBody);
if (isset($contentType) && $contentType) {
$contentTypeHeader['content-type'] = $contentType;
$this->request->setRequestHeaders($contentTypeHeader);
}
}
private function transformToUploadUrl()
{
$base = $this->request->getBaseComponent();
$this->request->setBaseComponent($base . '/upload');
}
/**
* Valid upload types:
* - resumable (UPLOAD_RESUMABLE_TYPE)
* - media (UPLOAD_MEDIA_TYPE)
* - multipart (UPLOAD_MULTIPART_TYPE)
* @param $meta
* @return string
* @visible for testing
*/
public function getUploadType($meta)
{
if ($this->resumable) {
return self::UPLOAD_RESUMABLE_TYPE;
}
if (false == $meta && $this->data) {
return self::UPLOAD_MEDIA_TYPE;
}
return self::UPLOAD_MULTIPART_TYPE;
}
private function getResumeUri()
{
$result = null;
$body = $this->request->getPostBody();
if ($body) {
$headers = array(
'content-type' => 'application/json; charset=UTF-8',
'content-length' => Google_Utils::getStrLen($body),
'x-upload-content-type' => $this->mimeType,
'x-upload-content-length' => $this->size,
'expect' => '',
);
$this->request->setRequestHeaders($headers);
}
$response = $this->client->getIo()->makeRequest($this->request);
$location = $response->getResponseHeader('location');
$code = $response->getResponseHttpCode();
if (200 == $code && true == $location) {
return $location;
}
$message = $code;
$body = @json_decode($response->getResponseBody());
if (!empty( $body->error->errors ) ) {
$message .= ': ';
foreach ($body->error->errors as $error) {
$message .= "{$error->domain}, {$error->message};";
}
$message = rtrim($message, ';');
}
$error = "Failed to start the resumable upload (HTTP {$message})";
$this->client->getLogger()->error($error);
throw new Google_Exception($error);
}
}
<?php
/*
* Copyright 2010 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
/**
* This class implements the RESTful transport of apiServiceRequest()'s
*/
class Google_Http_REST
{
/**
* Executes a Google_Http_Request and (if applicable) automatically retries
* when errors occur.
*
* @param Google_Client $client
* @param Google_Http_Request $req
* @return array decoded result
* @throws Google_Service_Exception on server side error (ie: not authenticated,
* invalid or malformed post body, invalid url)
*/
public static function execute(Google_Client $client, Google_Http_Request $req)
{
$runner = new Google_Task_Runner(
$client,
sprintf('%s %s', $req->getRequestMethod(), $req->getUrl()),
array(get_class(), 'doExecute'),
array($client, $req)
);
return $runner->run();
}
/**
* Executes a Google_Http_Request
*
* @param Google_Client $client
* @param Google_Http_Request $req
* @return array decoded result
* @throws Google_Service_Exception on server side error (ie: not authenticated,
* invalid or malformed post body, invalid url)
*/
public static function doExecute(Google_Client $client, Google_Http_Request $req)
{
$httpRequest = $client->getIo()->makeRequest($req);
$httpRequest->setExpectedClass($req->getExpectedClass());
return self::decodeHttpResponse($httpRequest, $client);
}
/**
* Decode an HTTP Response.
* @static
* @throws Google_Service_Exception
* @param Google_Http_Request $response The http response to be decoded.
* @param Google_Client $client
* @return mixed|null
*/
public static function decodeHttpResponse($response, Google_Client $client = null)
{
$code = $response->getResponseHttpCode();
$body = $response->getResponseBody();
$decoded = null;
if ((intVal($code)) >= 300) {
$decoded = json_decode($body, true);
$err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
if (isset($decoded['error']) &&
isset($decoded['error']['message']) &&
isset($decoded['error']['code'])) {
// if we're getting a json encoded error definition, use that instead of the raw response
// body for improved readability
$err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
} else {
$err .= ": ($code) $body";
}
$errors = null;
// Specific check for APIs which don't return error details, such as Blogger.
if (isset($decoded['error']) && isset($decoded['error']['errors'])) {
$errors = $decoded['error']['errors'];
}
$map = null;
if ($client) {
$client->getLogger()->error(
$err,
array('code' => $code, 'errors' => $errors)
);
$map = $client->getClassConfig(
'Google_Service_Exception',
'retry_map'
);
}
throw new Google_Service_Exception($err, $code, null, $errors, $map);
}
// Only attempt to decode the response, if the response code wasn't (204) 'no content'
if ($code != '204') {
if ($response->getExpectedRaw()) {
return $body;
}
$decoded = json_decode($body, true);
if ($decoded === null || $decoded === "") {
$error = "Invalid json in service response: $body";
if ($client) {
$client->getLogger()->error($error);
}
throw new Google_Service_Exception($error);
}
if ($response->getExpectedClass()) {
$class = $response->getExpectedClass();
$decoded = new $class($decoded);
}
}
return $decoded;
}
/**
* Parse/expand request parameters and create a fully qualified
* request uri.
* @static
* @param string $servicePath
* @param string $restPath
* @param array $params
* @return string $requestUrl
*/
public static function createRequestUri($servicePath, $restPath, $params)
{
$requestUrl = $servicePath . $restPath;
$uriTemplateVars = array();
$queryVars = array();
foreach ($params as $paramName => $paramSpec) {
if ($paramSpec['type'] == 'boolean') {
$paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
}
if ($paramSpec['location'] == 'path') {
$uriTemplateVars[$paramName] = $paramSpec['value'];
} else if ($paramSpec['location'] == 'query') {
if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
foreach ($paramSpec['value'] as $value) {
$queryVars[] = $paramName . '=' . rawurlencode($value);
}
} else {
$queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
}
}
}
if (count($uriTemplateVars)) {
$uriTemplateParser = new Google_Utils_URITemplate();
$requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
}
if (count($queryVars)) {
$requestUrl .= '?' . implode($queryVars, '&');
}
return $requestUrl;
}
}
This diff is collapsed.
<?php
/*
* Copyright 2014 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.
*/
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/../autoload.php';
}
class Google_Logger_Exception extends Google_Exception
{
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment