コード例 #1
0
ファイル: Apc.php プロジェクト: DanMaiman/Awfulkid
 public function __construct(Postman_Google_Client $client)
 {
     if (!function_exists('apc_add')) {
         $error = "Apc functions not available";
         $client->getLogger()->error($error);
         throw new Postman_Google_Cache_Exception($error);
     }
     $this->client = $client;
 }
コード例 #2
0
ファイル: IoTest.php プロジェクト: rapier83/isaebooks
 public function testExecutorSelection()
 {
     $default = function_exists('curl_version') ? 'Postman_Google_IO_Curl' : 'Postman_Google_IO_Stream';
     $client = $this->getClient();
     $this->assertInstanceOf($default, $client->getIo());
     $config = new Postman_Google_Config();
     $config->setIoClass('Postman_Google_IO_Stream');
     $client = new Postman_Google_Client($config);
     $this->assertInstanceOf('Postman_Google_IO_Stream', $client->getIo());
 }
コード例 #3
0
ファイル: Batch.php プロジェクト: DanMaiman/Awfulkid
 public function parseResponse(Postman_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 Postman_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 = Postman_Google_Http_REST::decodeHttpResponse($response, $this->client);
                     $responses[$key] = $response;
                 } catch (Postman_Google_Service_Exception $e) {
                     // Store the exception as the response, so successful responses
                     // can be processed.
                     $responses[$key] = $e;
                 }
             }
         }
         return $responses;
     }
     return null;
 }
コード例 #4
0
ファイル: Abstract.php プロジェクト: DanMaiman/Awfulkid
 /**
  * @visible for testing.
  * @param Postman_Google_Http_Request $request
  * @return Postman_Google_Http_Request|bool Returns the cached object or
  * false if the operation was unsuccessful.
  */
 public function getCachedRequest(Postman_Google_Http_Request $request)
 {
     if (false === Postman_Google_Http_CacheParser::isRequestCacheable($request)) {
         return false;
     }
     return $this->client->getCache()->get($request->getCacheKey());
 }
コード例 #5
0
 private function getResumeUri()
 {
     $result = null;
     $body = $this->request->getPostBody();
     if ($body) {
         $headers = array('content-type' => 'application/json; charset=UTF-8', 'content-length' => Postman_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 Postman_Google_Exception($error);
 }
コード例 #6
0
ファイル: REST.php プロジェクト: DanMaiman/Awfulkid
 /**
  * Decode an HTTP Response.
  * @static
  * @throws Postman_Google_Service_Exception
  * @param Postman_Google_Http_Request $response The http response to be decoded.
  * @param Postman_Google_Client $client
  * @return mixed|null
  */
 public static function decodeHttpResponse($response, Postman_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'];
         }
         if ($client) {
             $client->getLogger()->error($err, array('code' => $code, 'errors' => $errors));
         }
         throw new Postman_Google_Service_Exception($err, $code, null, $errors);
     }
     // Only attempt to decode the response, if the response code wasn't (204) 'no content'
     if ($code != '204') {
         $decoded = json_decode($body, true);
         if ($decoded === null || $decoded === "") {
             $error = "Invalid json in service response: {$body}";
             if ($client) {
                 $client->getLogger()->error($error);
             }
             throw new Postman_Google_Service_Exception($error);
         }
         if ($response->getExpectedClass()) {
             $class = $response->getExpectedClass();
             $decoded = new $class($decoded);
         }
     }
     return $decoded;
 }
コード例 #7
0
 /**
  * (non-PHPdoc)
  *
  * @see PostmanZendModuleTransport::createZendMailTransport()
  */
 public function createZendMailTransport($fakeHostname, $fakeConfig)
 {
     if (PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 == $this->getAuthenticationType()) {
         $config = PostmanOAuth2ConfigurationFactory::createConfig($this);
     } else {
         $config = PostmanBasicAuthConfigurationFactory::createConfig($this);
     }
     // Google's autoloader will try and load this so we list it first
     require_once 'PostmanGmailApiModuleZendMailTransport.php';
     // Gmail Client includes
     require_once 'google-api-php-client-1.1.2/src/Google/Client.php';
     require_once 'google-api-php-client-1.1.2/src/Google/Service/Gmail.php';
     // build the Gmail Client
     $authToken = PostmanOAuthToken::getInstance();
     $client = new Postman_Google_Client();
     $client->setClientId($this->options->getClientId());
     $client->setClientSecret($this->options->getClientSecret());
     $client->setRedirectUri('');
     // rebuild the google access token
     $token = new stdClass();
     $token->access_token = $authToken->getAccessToken();
     $token->refresh_token = $authToken->getRefreshToken();
     $token->token_type = 'Bearer';
     $token->expires_in = 3600;
     $token->id_token = null;
     $token->created = 0;
     $client->setAccessToken(json_encode($token));
     // We only need permissions to compose and send emails
     $client->addScope("https://www.googleapis.com/auth/gmail.compose");
     $service = new Postman_Google_Service_Gmail($client);
     $config[PostmanGmailApiModuleZendMailTransport::SERVICE_OPTION] = $service;
     return new PostmanGmailApiModuleZendMailTransport(self::HOST, $config);
 }
コード例 #8
0
ファイル: BaseTest.php プロジェクト: rapier83/isaebooks
 public function getClient()
 {
     $client = new Postman_Google_Client();
     $client->setDeveloperKey(self::KEY);
     if (strlen($this->token)) {
         $client->setAccessToken($this->token);
     }
     if (strlen($this->memcacheHost)) {
         $client->setClassConfig('Postman_Google_Cache_Memcache', 'host', $this->memcacheHost);
         $client->setClassConfig('Postman_Google_Cache_Memcache', 'port', $this->memcachePort);
     }
     return $client;
 }
コード例 #9
0
ファイル: Memcache.php プロジェクト: DanMaiman/Awfulkid
 public function __construct(Postman_Google_Client $client)
 {
     if (!function_exists('memcache_connect') && !class_exists("Memcached")) {
         $error = "Memcache functions not available";
         $client->getLogger()->error($error);
         throw new Postman_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 Postman_Google_Cache_Exception($error);
         }
     }
 }
コード例 #10
0
ファイル: fileupload.php プロジェクト: rapier83/isaebooks
DEFINE("TESTFILE", 'testfile.txt');
if (!file_exists(TESTFILE)) {
    $fh = fopen(TESTFILE, 'w');
    fseek($fh, 1024 * 1024 * 20);
    fwrite($fh, "!", 1);
    fclose($fh);
}
/************************************************
  ATTENTION: Fill in these values! Make sure
  the redirect URI is to this page, e.g:
  http://localhost:8080/fileupload.php
 ************************************************/
$client_id = '<YOUR_CLIENT_ID>';
$client_secret = '<YOUR_CLIENT_SECRET>';
$redirect_uri = '<YOUR_REDIRECT_URI>';
$client = new Postman_Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Postman_Google_Service_Drive($client);
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['upload_token ']);
}
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['upload_token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) {
コード例 #11
0
ファイル: Abstract.php プロジェクト: DanMaiman/Awfulkid
 /**
  * @param Postman_Google_Client $client  The current Google client
  */
 public function __construct(Postman_Google_Client $client)
 {
     $this->setLevel($client->getClassConfig('Postman_Google_Logger_Abstract', 'level'));
     $format = $client->getClassConfig('Postman_Google_Logger_Abstract', 'log_format');
     $this->logFormat = $format ? $format : self::DEFAULT_LOG_FORMAT;
     $format = $client->getClassConfig('Postman_Google_Logger_Abstract', 'date_format');
     $this->dateFormat = $format ? $format : self::DEFAULT_DATE_FORMAT;
     $this->allowNewLines = (bool) $client->getClassConfig('Postman_Google_Logger_Abstract', 'allow_newlines');
 }
コード例 #12
0
ファイル: batch.php プロジェクト: rapier83/isaebooks
 */
include_once "templates/base.php";
echo pageHeader("Batching Queries");
/************************************************
  We're going to use the simple access to the
  books API again as an example, but this time we
  will batch up two queries into a single call.
 ************************************************/
require_once realpath(dirname(__FILE__) . '/../autoload.php');
/************************************************
  We create the client and set the simple API
  access key. If you comment out the call to
  setDeveloperKey, the request may still succeed
  using the anonymous quota.
 ************************************************/
$client = new Postman_Google_Client();
$client->setApplicationName("Client_Library_Examples");
$apiKey = "<YOUR_API_KEY>";
// Change to your API key.
// Warn if the API key isn't changed!
if ($apiKey == '<YOUR_API_KEY>') {
    echo missingApiKeyWarning();
} else {
    $client->setDeveloperKey($apiKey);
    $service = new Postman_Google_Service_Books($client);
    /************************************************
        To actually make the batch call we need to 
        enable batching on the client - this will apply 
        globally until we set it to false. This causes
        call to the service methods to return the query
        rather than immediately executing.
コード例 #13
0
 /**
  * This is the only place where the Google library is loaded
  *
  * @see PostmanTransport::createZendMailTransport()
  */
 public function createZendMailTransport($hostname, $config)
 {
     // This is where the ZendMail special transport is loaded
     require_once 'PostmanGmailApiModuleZendMailTransport.php';
     // This is the only place where the Google library is loaded
     require_once 'google-api-php-client-1.1.2/src/Google/Client.php';
     require_once 'google-api-php-client-1.1.2/src/Google/Service/Gmail.php';
     // build the Gmail Client
     $options = PostmanOptions::getInstance();
     $authToken = PostmanOAuthToken::getInstance();
     $client = new Postman_Google_Client();
     $client->setClientId($options->getClientId());
     $client->setClientSecret($options->getClientSecret());
     $client->setRedirectUri('');
     // rebuild the google access token
     $token = new stdClass();
     $token->access_token = $authToken->getAccessToken();
     $token->refresh_token = $authToken->getRefreshToken();
     $token->token_type = 'Bearer';
     $token->expires_in = 3600;
     $token->id_token = null;
     $token->created = 0;
     $client->setAccessToken(json_encode($token));
     // We only need permissions to compose and send emails
     $client->addScope("https://www.googleapis.com/auth/gmail.compose");
     $service = new Postman_Google_Service_Gmail($client);
     $config[PostmanGmailApiModuleZendMailTransport::SERVICE_OPTION] = $service;
     return new PostmanGmailApiModuleZendMailTransport($hostname, $config);
 }
コード例 #14
0
ファイル: simple-query.php プロジェクト: rapier83/isaebooks
/************************************************
  Make a simple API request using a key. In this
  example we're not making a request as a
  specific user, but simply indicating that the
  request comes from our application, and hence
  should use our quota, which is higher than the
  anonymous quota (which is limited per IP).
 ************************************************/
require_once realpath(dirname(__FILE__) . '/../autoload.php');
/************************************************
  We create the client and set the simple API
  access key. If you comment out the call to
  setDeveloperKey, the request may still succeed
  using the anonymous quota.
 ************************************************/
$client = new Postman_Google_Client();
$client->setApplicationName("Client_Library_Examples");
$apiKey = "<YOUR_API_KEY>";
// Change this line.
// Warn if the API key isn't changed.
if ($apiKey == '<YOUR_API_KEY>') {
    echo missingApiKeyWarning();
}
$client->setDeveloperKey($apiKey);
$service = new Postman_Google_Service_Books($client);
/************************************************
  We make a call to our service, which will
  normally map to the structure of the API.
  In this case $service is Books API, the
  resource is volumes, and the method is
  listVolumes. We pass it a required parameters
コード例 #15
0
ファイル: ApiClientTest.php プロジェクト: rapier83/isaebooks
 public function testJsonConfig()
 {
     // Device config
     $config = new Postman_Google_Config();
     $client = new Postman_Google_Client($config);
     $device = '{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret"' . ':"N0aHCBT1qX1VAcF5J1pJAn6S","token_uri":"https://accounts.google.com/o/oauth2/token",' . '"client_email":"","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","oob"],"client_x509_cert_url"' . ':"","client_id":"123456789.apps.googleusercontent.com","auth_provider_x509_cert_url":' . '"https://www.googleapis.com/oauth2/v1/certs"}}';
     $dObj = json_decode($device);
     $client->setAuthConfig($device);
     $cfg = $config->getClassConfig('Postman_Google_Auth_OAuth2');
     $this->assertEquals($cfg['client_id'], $dObj->installed->client_id);
     $this->assertEquals($cfg['client_secret'], $dObj->installed->client_secret);
     $this->assertEquals($cfg['redirect_uri'], $dObj->installed->redirect_uris[0]);
     // Web config
     $config = new Postman_Google_Config();
     $client = new Postman_Google_Client($config);
     $web = '{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret"' . ':"lpoubuib8bj-Fmke_YhhyHGgXc","token_uri":"https://accounts.google.com/o/oauth2/token"' . ',"client_email":"*****@*****.**","client_x509_cert_url":' . '"https://www.googleapis.com/robot/v1/metadata/x509/123456789@developer.gserviceaccount.com"' . ',"client_id":"123456789.apps.googleusercontent.com","auth_provider_x509_cert_url":' . '"https://www.googleapis.com/oauth2/v1/certs"}}';
     $wObj = json_decode($web);
     $client->setAuthConfig($web);
     $cfg = $config->getClassConfig('Postman_Google_Auth_OAuth2');
     $this->assertEquals($cfg['client_id'], $wObj->web->client_id);
     $this->assertEquals($cfg['client_secret'], $wObj->web->client_secret);
     $this->assertEquals($cfg['redirect_uri'], '');
 }
コード例 #16
0
ファイル: ApiOAuth2Test.php プロジェクト: rapier83/isaebooks
 /**
  * Test that the ID token is properly refreshed.
  */
 public function testRefreshTokenSetsValues()
 {
     $client = new Postman_Google_Client();
     $response_data = json_encode(array('access_token' => "ACCESS_TOKEN", 'id_token' => "ID_TOKEN", 'expires_in' => "12345"));
     $response = $this->getMock("Postman_Google_Http_Request", array(), array(''));
     $response->expects($this->any())->method('getResponseHttpCode')->will($this->returnValue(200));
     $response->expects($this->any())->method('getResponseBody')->will($this->returnValue($response_data));
     $io = $this->getMock("Postman_Google_IO_Stream", array(), array($client));
     $io->expects($this->any())->method('makeRequest')->will($this->returnCallback(function ($request) use(&$token, $response) {
         $elements = $request->getPostBody();
         PHPUnit_Framework_TestCase::assertEquals($elements['grant_type'], "refresh_token");
         PHPUnit_Framework_TestCase::assertEquals($elements['refresh_token'], "REFRESH_TOKEN");
         return $response;
     }));
     $client->setIo($io);
     $oauth = new Postman_Google_Auth_OAuth2($client);
     $oauth->refreshToken("REFRESH_TOKEN");
     $token = json_decode($oauth->getAccessToken(), true);
     $this->assertEquals($token['id_token'], "ID_TOKEN");
 }
コード例 #17
0
ファイル: idtoken.php プロジェクト: rapier83/isaebooks
 * 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.
 */
include_once "templates/base.php";
session_start();
require_once realpath(dirname(__FILE__) . '/../autoload.php');
/************************************************
  ATTENTION: Fill in these values! Make sure
  the redirect URI is to this page, e.g:
  http://localhost:8080/user-example.php
 ************************************************/
$client_id = '<YOUR_CLIENT_ID>';
$client_secret = '<YOUR_CLIENT_SECRET>';
$redirect_uri = '<YOUR_REDIRECT_URI>';
$client = new Postman_Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes('email');
/************************************************
  If we're logging out we just need to clear our
  local access token in this case
 ************************************************/
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['access_token']);
}
/************************************************
  If we have a code back from the OAuth 2.0 flow,
  we need to exchange that with the authenticate()
  function. We store the resultant access token
コード例 #18
0
ファイル: appengineauth.php プロジェクト: rapier83/isaebooks
 *     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.
 */
session_start();
include_once "templates/base.php";
/************************************************
  Make an API request authenticated via the 
  AppIdentity service on AppEngine.
 ************************************************/
require_once realpath(dirname(__FILE__) . '/../autoload.php');
echo pageHeader("AppIdentity Account Access");
$client = new Postman_Google_Client();
$client->setApplicationName("Client_Library_Examples");
$auth = new Postman_Google_Auth_AppIdentity($client);
$token = $auth->authenticateForScope(Postman_Google_Service_Storage::DEVSTORAGE_READ_ONLY);
if (!$token) {
    die("Could not authenticate to AppIdentity service");
}
$client->setAuth($auth);
$service = new Postman_Google_Service_Storage($client);
$results = $service->buckets->listBuckets(str_replace("s~", "", $_SERVER['APPLICATION_ID']));
echo "<h3>Results Of Call:</h3>";
echo "<pre>";
var_dump($results);
echo "</pre>";
echo pageFooter(__FILE__);
コード例 #19
0
ファイル: multi-api.php プロジェクト: rapier83/isaebooks
/************************************************
  ATTENTION: Fill in these values! Make sure
  the redirect URI is to this page, e.g:
  http://localhost:8080/user-example.php
 ************************************************/
$client_id = '<YOUR_CLIENT_ID>';
$client_secret = '<YOUR_CLIENT_SECRET>';
$redirect_uri = '<YOUR_REDIRECT_URI>';
/************************************************
  Make an API request on behalf of a user. In
  this case we need to have a valid OAuth 2.0
  token for the user, so we need to send them
  through a login flow. To do this we need some
  information from our API console project.
 ************************************************/
$client = new Postman_Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$client->addScope("https://www.googleapis.com/auth/youtube");
/************************************************
  We are going to create both YouTube and Drive
  services, and query both.
 ************************************************/
$yt_service = new Postman_Google_Service_YouTube($client);
$dr_service = new Postman_Google_Service_Drive($client);
/************************************************
  Boilerplate auth management - see
  user-example.php for details.
 ************************************************/
コード例 #20
0
ファイル: Resource.php プロジェクト: DanMaiman/Awfulkid
 /**
  * TODO(ianbarber): This function needs simplifying.
  * @param $name
  * @param $arguments
  * @param $expected_class - optional, the expected class name
  * @return Postman_Google_Http_Request|expected_class
  * @throws Postman_Google_Exception
  */
 public function call($name, $arguments, $expected_class = null)
 {
     if (!isset($this->methods[$name])) {
         $this->client->getLogger()->error('Service method unknown', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name));
         throw new Postman_Google_Exception("Unknown function: " . "{$this->serviceName}->{$this->resourceName}->{$name}()");
     }
     $method = $this->methods[$name];
     $parameters = $arguments[0];
     // postBody is a special case since it's not defined in the discovery
     // document as parameter, but we abuse the param entry for storing it.
     $postBody = null;
     if (isset($parameters['postBody'])) {
         if ($parameters['postBody'] instanceof Postman_Google_Model) {
             // In the cases the post body is an existing object, we want
             // to use the smart method to create a simple object for
             // for JSONification.
             $parameters['postBody'] = $parameters['postBody']->toSimpleObject();
         } else {
             if (is_object($parameters['postBody'])) {
                 // If the post body is another kind of object, we will try and
                 // wrangle it into a sensible format.
                 $parameters['postBody'] = $this->convertToArrayAndStripNulls($parameters['postBody']);
             }
         }
         $postBody = json_encode($parameters['postBody']);
         unset($parameters['postBody']);
     }
     // TODO(ianbarber): optParams here probably should have been
     // handled already - this may well be redundant code.
     if (isset($parameters['optParams'])) {
         $optParams = $parameters['optParams'];
         unset($parameters['optParams']);
         $parameters = array_merge($parameters, $optParams);
     }
     if (!isset($method['parameters'])) {
         $method['parameters'] = array();
     }
     $method['parameters'] = array_merge($method['parameters'], $this->stackParameters);
     foreach ($parameters as $key => $val) {
         if ($key != 'postBody' && !isset($method['parameters'][$key])) {
             $this->client->getLogger()->error('Service parameter unknown', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'parameter' => $key));
             throw new Postman_Google_Exception("({$name}) unknown parameter: '{$key}'");
         }
     }
     foreach ($method['parameters'] as $paramName => $paramSpec) {
         if (isset($paramSpec['required']) && $paramSpec['required'] && !isset($parameters[$paramName])) {
             $this->client->getLogger()->error('Service parameter missing', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'parameter' => $paramName));
             throw new Postman_Google_Exception("({$name}) missing required param: '{$paramName}'");
         }
         if (isset($parameters[$paramName])) {
             $value = $parameters[$paramName];
             $parameters[$paramName] = $paramSpec;
             $parameters[$paramName]['value'] = $value;
             unset($parameters[$paramName]['required']);
         } else {
             // Ensure we don't pass nulls.
             unset($parameters[$paramName]);
         }
     }
     $servicePath = $this->service->servicePath;
     $this->client->getLogger()->info('Service Call', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'arguments' => $parameters));
     $url = Postman_Google_Http_REST::createRequestUri($servicePath, $method['path'], $parameters);
     $httpRequest = new Postman_Google_Http_Request($url, $method['httpMethod'], null, $postBody);
     $httpRequest->setBaseComponent($this->client->getBasePath());
     if ($postBody) {
         $contentTypeHeader = array();
         $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
         $httpRequest->setRequestHeaders($contentTypeHeader);
         $httpRequest->setPostBody($postBody);
     }
     $httpRequest = $this->client->getAuth()->sign($httpRequest);
     $httpRequest->setExpectedClass($expected_class);
     if (isset($parameters['data']) && ($parameters['uploadType']['value'] == 'media' || $parameters['uploadType']['value'] == 'multipart')) {
         // If we are doing a simple media upload, trigger that as a convenience.
         $mfu = new Postman_Google_Http_MediaFileUpload($this->client, $httpRequest, isset($parameters['mimeType']) ? $parameters['mimeType']['value'] : 'application/octet-stream', $parameters['data']['value']);
     }
     if ($this->client->shouldDefer()) {
         // If we are in batch or upload mode, return the raw request.
         return $httpRequest;
     }
     return $this->client->execute($httpRequest);
 }
コード例 #21
0
  as part of the service account (not your
  address!)
  Make sure the Books API is enabled on this
  account as well, or the call will fail.
 ************************************************/
$client_id = '<YOUR_CLIENT_ID>';
//Client ID
$service_account_name = '';
//Email Address
$key_file_location = '';
//key.p12
echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>' || !strlen($service_account_name) || !strlen($key_file_location)) {
    echo missingServiceAccountDetailsWarning();
}
$client = new Postman_Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Postman_Google_Service_Books($client);
/************************************************
  If we have an access token, we can carry on.
  Otherwise, we'll get one with the help of an
  assertion credential. In other examples the list
  of scopes was managed by the Client, but here
  we have to list them manually. We also supply
  the service account
 ************************************************/
if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Postman_Google_Auth_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/books'), $key);
コード例 #22
0
ファイル: OAuthHelper.php プロジェクト: rapier83/isaebooks
/*
 * 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.
 */
require_once dirname(__FILE__) . '/../autoload.php';
$client = new Postman_Google_Client();
$client->setScopes(array("https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/youtube"));
$client->setRedirectUri("urn:ietf:wg:oauth:2.0:oob");
// Visit https://code.google.com/apis/console to
// generate your oauth2_client_id, oauth2_client_secret, and to
// register your oauth2_redirect_uri.
$client->setClientId("");
$client->setClientSecret("");
$authUrl = $client->createAuthUrl();
`open '{$authUrl}'`;
echo "\nPlease enter the auth code:\n";
$authCode = trim(fgets(STDIN));
$accessToken = $client->authenticate($authCode);
echo "\n", 'Add the following to BaseTest.php as the $token value:', "\n\n";
echo $accessToken, "\n\n";