예제 #1
0
 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);
 }
예제 #2
0
 public function testIsResponseCacheable()
 {
     $client = $this->getClient();
     $resp = new Google_Http_Request('http://localhost', 'POST');
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertFalse($result);
     // The response has expired, and we don't have an etag for
     // revalidation.
     $resp = new Google_Http_Request('http://localhost', 'GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 1998 14:19:41 GMT', 'Date' => 'Mon, 29 Jun 1998 02:28:12 GMT', 'Last-Modified' => 'Mon, 29 Jun 1998 02:28:12 GMT'));
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertFalse($result);
     // Verify cacheable responses.
     $resp = new Google_Http_Request('http://localhost', 'GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'ETag' => '3e86-410-3596fbbc'));
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertTrue($result);
     // Verify that responses to HEAD requests are cacheable.
     $resp = new Google_Http_Request('http://localhost', 'HEAD');
     $resp->setResponseHttpCode('200');
     $resp->setResponseBody(null);
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'ETag' => '3e86-410-3596fbbc'));
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertTrue($result);
     // Verify that Vary: * cannot get cached.
     $resp = new Google_Http_Request('http://localhost', 'GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Date' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'Vary' => 'foo', 'ETag' => '3e86-410-3596fbbc'));
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertFalse($result);
     // Verify 201s cannot get cached.
     $resp = new Google_Http_Request('http://localhost', 'GET');
     $resp->setResponseHttpCode('201');
     $resp->setResponseBody(null);
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'ETag' => '3e86-410-3596fbbc'));
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertFalse($result);
     // Verify pragma: no-cache.
     $resp = new Google_Http_Request('http://localhost', 'GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Expires' => 'Wed, 11 Jan 2012 04:03:37 GMT', 'Date' => 'Wed, 11 Jan 2012 04:03:37 GMT', 'Pragma' => 'no-cache', 'Cache-Control' => 'private, max-age=0, must-revalidate, no-transform', 'ETag' => '3e86-410-3596fbbc'));
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertFalse($result);
     // Verify Cache-Control: no-store.
     $resp = new Google_Http_Request('http://localhost', 'GET');
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Expires' => 'Wed, 11 Jan 2012 04:03:37 GMT', 'Date' => 'Wed, 11 Jan 2012 04:03:37 GMT', 'Cache-Control' => 'no-store', 'ETag' => '3e86-410-3596fbbc'));
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertFalse($result);
     // Verify that authorized responses are not cacheable.
     $resp = new Google_Http_Request('http://localhost', 'GET');
     $resp->setRequestHeaders(array('Authorization' => 'Bearer Token'));
     $resp->setResponseHttpCode('200');
     $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => 'Fri, 30 Oct 2013 14:19:41 GMT', 'Last-Modified' => 'Mon, 29 Jun 2011 02:28:12 GMT', 'ETag' => '3e86-410-3596fbbc'));
     $result = Google_Http_CacheParser::isResponseCacheable($resp);
     $this->assertFalse($result);
 }
 public function sign(Google_Http_Request $request)
 {
     $this->key = $this->client->getClassConfig($this, 'key');
     if ($this->key) {
         $request->setRequestHeaders(array('Authorization' => $this->key));
     }
     return $request;
 }
예제 #4
0
 public function sign(Google_Http_Request $request)
 {
     if (!$this->token) {
         // No token, so nothing to do.
         return $request;
     }
     // Add the OAuth2 header to the request
     $request->setRequestHeaders(array('Authorization' => 'Bearer ' . $this->token['access_token']));
     return $request;
 }
예제 #5
0
 public function authCache($io, $client)
 {
     $url = "http://www.googleapis.com/protected/resource";
     // Create a cacheable request/response, but it should not be cached.
     $cacheReq = new Google_Http_Request($client, $url, "GET");
     $cacheReq->setRequestHeaders(array("Accept" => "*/*", "Authorization" => "Bearer Foo"));
     $cacheReq->setResponseBody("{\"a\": \"foo\"}");
     $cacheReq->setResponseHttpCode(200);
     $cacheReq->setResponseHeaders(array("Cache-Control" => "private", "ETag" => "\"this-is-an-etag\"", "Expires" => "Sun, 22 Jan 2022 09:00:56 GMT", "Date: Sun, 1 Jan 2012 09:00:56 GMT", "Content-Type" => "application/json; charset=UTF-8"));
     $result = $io->setCachedRequest($cacheReq);
     $this->assertFalse($result);
 }
예제 #6
0
 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;
     }
     throw new Google_Exception("Failed to start the resumable upload");
 }
예제 #7
0
 public function execute()
 {
     $body = '';
     /** @var Google_Http_Request $req */
     foreach ($this->requests as $key => $req) {
         $body .= "--{$this->boundary}\n";
         $body .= $req->toBatchString($key) . "\n\n";
         $this->expected_classes["response-" . $key] = $req->getExpectedClass();
     }
     $body .= "--{$this->boundary}--";
     $url = $this->root_url . '/' . $this->batch_path;
     $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);
 }
예제 #8
0
파일: Resource.php 프로젝트: nabble/ajde
 /**
  * TODO(ianbarber): This function needs simplifying.
  *
  * @param $name
  * @param $arguments
  * @param $expected_class - optional, the expected class name
  *
  * @throws Google_Exception
  *
  * @return Google_Http_Request|expected_class
  */
 public function call($name, $arguments, $expected_class = null)
 {
     if (!isset($this->methods[$name])) {
         throw new 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 (is_object($parameters['postBody'])) {
             $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'] = [];
     }
     $method['parameters'] = array_merge($method['parameters'], $this->stackParameters);
     foreach ($parameters as $key => $val) {
         if ($key != 'postBody' && !isset($method['parameters'][$key])) {
             throw new Google_Exception("({$name}) unknown parameter: '{$key}'");
         }
     }
     foreach ($method['parameters'] as $paramName => $paramSpec) {
         if (isset($paramSpec['required']) && $paramSpec['required'] && !isset($parameters[$paramName])) {
             throw new 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;
     $url = Google_Http_REST::createRequestUri($servicePath, $method['path'], $parameters);
     $httpRequest = new Google_Http_Request($this->client, $url, $method['httpMethod'], null, $postBody);
     if ($postBody) {
         $contentTypeHeader = [];
         $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 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 $httpRequest->execute();
 }
예제 #9
0
 /**
  * TODO(ianbarber): This function needs simplifying.
  * @param $name
  * @param $arguments
  * @param $expected_class - optional, the expected class name
  * @return Google_Http_Request|expected_class
  * @throws 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 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 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 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 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]);
         }
     }
     $this->client->getLogger()->info('Service Call', array('service' => $this->serviceName, 'resource' => $this->resourceName, 'method' => $name, 'arguments' => $parameters));
     $url = Google_Http_REST::createRequestUri($this->servicePath, $method['path'], $parameters);
     $httpRequest = new Google_Http_Request($url, $method['httpMethod'], null, $postBody);
     if ($this->rootUrl) {
         $httpRequest->setBaseComponent($this->rootUrl);
     } else {
         $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 Google_Http_MediaFileUpload($this->client, $httpRequest, isset($parameters['mimeType']) ? $parameters['mimeType']['value'] : 'application/octet-stream', $parameters['data']['value']);
     }
     if (isset($parameters['alt']) && $parameters['alt']['value'] == 'media') {
         $httpRequest->enableExpectedRaw();
     }
     if ($this->client->shouldDefer()) {
         // If we are in batch or upload mode, return the raw request.
         return $httpRequest;
     }
     return $this->client->execute($httpRequest);
 }
 public static function delete(Contact $toDelete)
 {
     $client = GoogleHelper::getClient();
     $req = new \Google_Http_Request($toDelete->editURL);
     $req->setRequestHeaders(array('content-type' => 'application/atom+xml; charset=UTF-8; type=feed'));
     $req->setRequestMethod('DELETE');
     $client->getAuth()->authenticatedRequest($req);
 }
예제 #11
0
 /**
  * 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)
 {
     // add the developer key to the request before signing it
     if ($this->client->getClassConfig($this, 'developer_key')) {
         $request->setQueryParam('key', $this->client->getClassConfig($this, 'developer_key'));
     }
     // Cannot sign the request without an OAuth access token.
     if (null == $this->token && null == $this->assertionCredentials) {
         return $request;
     }
     // Check if the token is set to expire in the next 30 seconds
     // (or has already expired).
     if ($this->isAccessTokenExpired()) {
         if ($this->assertionCredentials) {
             $this->refreshTokenWithAssertion();
         } else {
             $this->client->getLogger()->debug('OAuth2 access token expired');
             if (!array_key_exists('refresh_token', $this->token)) {
                 $error = "The OAuth 2.0 access token has expired," . " and a refresh token is not available. Refresh tokens" . " are not returned for responses that were auto-approved.";
                 $this->client->getLogger()->error($error);
                 throw new Google_Auth_Exception($error);
             }
             $this->refreshToken($this->token['refresh_token']);
         }
     }
     $this->client->getLogger()->debug('OAuth2 authentication');
     // Add the OAuth2 header to the request
     $request->setRequestHeaders(array('Authorization' => 'Bearer ' . $this->token['access_token']));
     return $request;
 }
예제 #12
0
 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;
 }
예제 #13
0
 /**
  * Check if an already cached request must be revalidated, and if so update
  * the request with the correct ETag headers.
  * @param Google_Http_Request $cached A previously cached response.
  * @param Google_Http_Request $request The outbound request.
  * return bool If the cached object needs to be revalidated, false if it is
  * still current and can be re-used.
  */
 protected function checkMustRevalidateCachedRequest($cached, $request)
 {
     if (Google_Http_CacheParser::mustRevalidate($cached)) {
         $addHeaders = array();
         if ($cached->getResponseHeader('etag')) {
             // [13.3.4] If an entity tag has been provided by the origin server,
             // we must use that entity tag in any cache-conditional request.
             $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
         } elseif ($cached->getResponseHeader('date')) {
             $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
         }
         $request->setRequestHeaders($addHeaders);
         return true;
     } else {
         return false;
     }
 }
 /**
  * Sends the authenticated request to Gitkit API. The request contains an
  * OAuth2 access_token generated from service account.
  *
  * @param string $method the API method name
  * @param array $data http post data for the api
  * @return array server response
  * @throws Gitkit_ClientException if input is invalid
  * @throws Gitkit_ServerException if there is server error
  */
 public function invokeGitkitApiWithServiceAccount($method, $data)
 {
     $httpRequest = new Google_Http_Request($this->gitkitApisUrl . $method, 'POST', null, json_encode($data));
     $contentTypeHeader = array();
     $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
     $httpRequest->setRequestHeaders($contentTypeHeader);
     $response = $this->oauth2Client->authenticatedRequest($httpRequest)->getResponseBody();
     return $this->checkGitkitError(json_decode($response, true));
 }
예제 #15
0
 private static function _create_contact($client, $cid, $id, $name, $emailAddress, $phoneNumber, $industryGroup, $address, $comments, $company, $title, $birthday, $url, $referral, $manager, $workPhone, $cellPhone, $faxPhone)
 {
     $doc = new DOMDocument();
     $doc->formatOutput = true;
     $entry = $doc->createElement('atom:entry');
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:atom', 'http://www.w3.org/2005/Atom');
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gd', 'http://schemas.google.com/g/2005');
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gd', 'http://schemas.google.com/g/2005');
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gContact', 'http://schemas.google.com/contact/2008');
     $doc->appendChild($entry);
     if ($id !== false) {
         $idDom = $doc->createElement('id', $id);
         $entry->appendChild($idDom);
     }
     $categoryDom = $doc->createElement('category');
     $categoryDom->setAttribute('term', 'user-tag');
     $categoryDom->setAttribute('label', $industryGroup['title']);
     $entry->appendChild($categoryDom);
     $titleDom = $doc->createElement('title', $name);
     $entry->appendChild($titleDom);
     $contentDom = $doc->createElement('content', $comments);
     $entry->appendChild($contentDom);
     $emailDom = $doc->createElement('gd:email');
     $emailDom->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
     $emailDom->setAttribute('address', $emailAddress);
     $entry->appendChild($emailDom);
     if (!empty($phoneNumber)) {
         $phoneNumberDom = $doc->createElement('gd:phoneNumber', $phoneNumber);
         $phoneNumberDom->setAttribute('rel', 'http://schemas.google.com/g/2005#main');
         $phoneNumberDom->setAttribute('primary', 'true');
         $entry->appendChild($phoneNumberDom);
     }
     if (!empty($workPhone)) {
         $phoneNumberDom = $doc->createElement('gd:phoneNumber', $workPhone);
         $phoneNumberDom->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
         $entry->appendChild($phoneNumberDom);
     }
     if (!empty($cellPhone)) {
         $phoneNumberDom = $doc->createElement('gd:phoneNumber', $cellPhone);
         $phoneNumberDom->setAttribute('rel', 'http://schemas.google.com/g/2005#mobile');
         $entry->appendChild($phoneNumberDom);
     }
     if (!empty($faxPhone)) {
         $phoneNumberDom = $doc->createElement('gd:phoneNumber', $faxPhone);
         $phoneNumberDom->setAttribute('rel', 'http://schemas.google.com/g/2005#fax');
         $entry->appendChild($phoneNumberDom);
     }
     if (!empty($address)) {
         $postalAddressDom = $doc->createElement('gd:postalAddress', $address);
         $postalAddressDom->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
         $postalAddressDom->setAttribute('primary', 'true');
         $entry->appendChild($postalAddressDom);
     }
     if (!empty($company) || !empty($title)) {
         $orgDom = $doc->createElement('gd:organization');
         $orgDom->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
         $orgDom->setAttribute('primary', 'true');
         if (isset($company) && !empty($company)) {
             file_put_contents(dirname(__FILE__) . '/update.txt', PHP_EOL . 'Company: ' . PHP_EOL . var_export($company, true) . PHP_EOL, FILE_APPEND);
             $orgNameDom = $doc->createElement('gd:orgName', $company);
             $orgDom->appendChild($orgNameDom);
         }
         if (isset($title) && !empty($title)) {
             file_put_contents(dirname(__FILE__) . '/update.txt', PHP_EOL . 'Title: ' . PHP_EOL . var_export($title, true) . PHP_EOL, FILE_APPEND);
             $orgTitleDom = $doc->createElement('gd:orgTitle', $title);
             $orgDom->appendChild($orgTitleDom);
         }
         $entry->appendChild($orgDom);
     }
     if (!empty($referral)) {
         $referralDom = $doc->createElement('gd:extendedProperty');
         $referralDom->setAttribute('name', 'referral');
         $referralDom->setAttribute('value', $referral);
         $entry->appendChild($referralDom);
     }
     if (!empty($manager)) {
         $managerDom = $doc->createElement('gd:extendedProperty');
         $managerDom->setAttribute('name', 'manager');
         $managerDom->setAttribute('value', $manager);
         $entry->appendChild($managerDom);
     }
     if (!empty($birthday)) {
         $birthdayDom = $doc->createElement('gContact:birthday');
         $birthdayDom->setAttribute('when', $birthday);
         $entry->appendChild($birthdayDom);
     }
     $birthdayDom = $doc->createElement('gContact:relation');
     $birthdayDom->setAttribute('label', 'Ontraport Contact');
     $entry->appendChild($birthdayDom);
     if (!empty($url)) {
         $websiteDom = $doc->createElement('gContact:website');
         $websiteDom->setAttribute('href', $url);
         $websiteDom->setAttribute('rel', 'http://schemas.google.com/g/2005#profile');
         $websiteDom->setAttribute('primary', 'true');
         $entry->appendChild($websiteDom);
     }
     $groupMemDom = $doc->createElement('gContact:groupMembershipInfo');
     $groupMemDom->setAttribute('href', $industryGroup['id']);
     $groupMemDom->setAttribute('deleted', 'false');
     $entry->appendChild($groupMemDom);
     $xmlToSend = $doc->saveXML();
     file_put_contents(dirname(__FILE__) . '/update.txt', PHP_EOL . 'Request XML' . PHP_EOL . $xmlToSend . PHP_EOL, FILE_APPEND);
     if ($cid !== false) {
         file_put_contents(dirname(__FILE__) . '/update.txt', PHP_EOL . '%%%% Priming UPDATE request header with CID: ' . $cid, FILE_APPEND);
         $req = new Google_Http_Request('https://www.google.com/m8/feeds/contacts/default/full/' . $cid);
         $req->setRequestHeaders(array('content-type' => 'application/atom+xml; charset=UTF-8; type=feed'));
         $req->setRequestMethod('PUT');
         $req->setPostBody($xmlToSend);
     } else {
         file_put_contents(dirname(__FILE__) . '/update.txt', PHP_EOL . '++++ Priming CREATE request header', FILE_APPEND);
         $req = new Google_Http_Request('https://www.google.com/m8/feeds/contacts/default/full');
         $req->setRequestHeaders(array('content-type' => 'application/atom+xml; charset=UTF-8; type=feed'));
         $req->setRequestMethod('POST');
         $req->setPostBody($xmlToSend);
     }
     file_put_contents(dirname(__FILE__) . '/update.txt', PHP_EOL . 'Making request', FILE_APPEND);
     $val = $client->getAuth()->authenticatedRequest($req);
     $response = $val->getResponseBody();
     file_put_contents(dirname(__FILE__) . '/update.txt', PHP_EOL . PHP_EOL . '===RESPONSE===' . PHP_EOL . $response . PHP_EOL . PHP_EOL, FILE_APPEND);
     $xmlContact = simplexml_load_string($response);
     $xmlContact->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
     return OPContactProxy::xml2array($xmlContact);
 }
예제 #16
0
 /**
  * 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;
 }
예제 #17
0
function araa_registration_is_duplicate($client, $email)
{
    // Check if the user has already submitted a registration.
    $url = sprintf('https://spreadsheets.google.com/feeds/list/%s/%s/private/full?sq=%s', urlencode(get_option('araa_spreadsheet_id')), urlencode(get_option('araa_worksheet_id')), urlencode(sprintf('email="%s"', addslashes($email))));
    $request = new Google_Http_Request($url);
    $request->setRequestHeaders(array('Content-Type' => 'application/atom+xml'));
    try {
        $response = $client->getAuth()->authenticatedRequest($request);
        $existing = simplexml_load_string($response->getResponseBody());
        if ($existing) {
            $ns = 'http://a9.com/-/spec/opensearchrss/1.0/';
            $total = intval($existing->children($ns)->totalResults);
            return $total > 0;
        }
    } catch (Google_Auth_Exception $e) {
        // Don't worry about checking duplicates.
    }
    return false;
}
예제 #18
0
 public static function create($name, $phoneNumber, $emailAddress)
 {
     $doc = new \DOMDocument();
     $doc->formatOutput = true;
     $entry = $doc->createElement('atom:entry');
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:atom', 'http://www.w3.org/2005/Atom');
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gd', 'http://schemas.google.com/g/2005');
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gd', 'http://schemas.google.com/g/2005');
     $doc->appendChild($entry);
     $title = $doc->createElement('title', $name);
     $entry->appendChild($title);
     $email = $doc->createElement('gd:email');
     $email->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
     $email->setAttribute('address', $emailAddress);
     $entry->appendChild($email);
     $contact = $doc->createElement('gd:phoneNumber', $phoneNumber);
     $contact->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
     $entry->appendChild($contact);
     $xmlToSend = $doc->saveXML();
     $client = GoogleHelper::getClient();
     $req = new \Google_Http_Request('https://www.google.com/m8/feeds/contacts/default/full');
     $req->setRequestHeaders(array('content-type' => 'application/atom+xml; charset=UTF-8; type=feed'));
     $req->setRequestMethod('POST');
     $req->setPostBody($xmlToSend);
     $val = $client->getAuth()->authenticatedRequest($req);
     $response = $val->getResponseBody();
     $xmlContact = simplexml_load_string($response);
     $xmlContact->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
     $xmlContactsEntry = $xmlContact;
     $contactDetails = array();
     $contactDetails['id'] = (string) $xmlContactsEntry->id;
     $contactDetails['name'] = (string) $xmlContactsEntry->title;
     foreach ($xmlContactsEntry->children() as $key => $value) {
         $attributes = $value->attributes();
         if ($key == 'link') {
             if ($attributes['rel'] == 'edit') {
                 $contactDetails['editURL'] = (string) $attributes['href'];
             } elseif ($attributes['rel'] == 'self') {
                 $contactDetails['selfURL'] = (string) $attributes['href'];
             }
         }
     }
     $contactGDNodes = $xmlContactsEntry->children('http://schemas.google.com/g/2005');
     foreach ($contactGDNodes as $key => $value) {
         $attributes = $value->attributes();
         if ($key == 'email') {
             $contactDetails[$key] = (string) $attributes['address'];
         } elseif ($key == 'organization') {
             $contactDetails[$key] = 'hello';
             //$contactDetails[$key] = (string) $value->children()->current() ?: 'hello';
         } else {
             $contactDetails[$key] = (string) $value;
         }
     }
     return new Contact($contactDetails);
 }