public function __construct(GoogleGAL_Client $client)
 {
     if (!function_exists('apc_add')) {
         $error = "Apc functions not available";
         $client->getLogger()->error($error);
         throw new GoogleGAL_Cache_Exception($error);
     }
     $this->client = $client;
 }
 public function parseResponse(GoogleGAL_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 GoogleGAL_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 = GoogleGAL_Http_REST::decodeHttpResponse($response, $this->client);
                     $responses[$key] = $response;
                 } catch (GoogleGAL_Service_Exception $e) {
                     // Store the exception as the response, so successful responses
                     // can be processed.
                     $responses[$key] = $e;
                 }
             }
         }
         return $responses;
     }
     return null;
 }
 /**
  * @visible for testing.
  * @param GoogleGAL_Http_Request $request
  * @return GoogleGAL_Http_Request|bool Returns the cached object or
  * false if the operation was unsuccessful.
  */
 public function getCachedRequest(GoogleGAL_Http_Request $request)
 {
     if (false === GoogleGAL_Http_CacheParser::isRequestCacheable($request)) {
         return false;
     }
     return $this->client->getCache()->get($request->getCacheKey());
 }
 private function getResumeUri()
 {
     $result = null;
     $body = $this->request->getPostBody();
     if ($body) {
         $headers = array('content-type' => 'application/json; charset=UTF-8', 'content-length' => GoogleGAL_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 GoogleGAL_Exception($error);
 }
 public function __construct(GoogleGAL_Client $client)
 {
     if (!function_exists('memcache_connect') && !class_exists("Memcached")) {
         throw new GoogleGAL_Cache_Exception("Memcache functions not available");
     }
     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)) {
             throw new GoogleGAL_Cache_Exception("You need to supply a valid memcache host and port");
         }
     }
 }
 protected function createGoogleClient($options, $includeoauth = false)
 {
     // Another plugin might have already included these files
     // Unfortunately we just have to hope they have a similar enough version
     set_include_path(get_include_path() . PATH_SEPARATOR . plugin_dir_path(__FILE__));
     // Google PHP Client obtained from https://github.com/google/google-api-php-client
     // Using modified Google Client to avoid name clashes - rename process:
     // find . -type f -exec sed -i '' -e 's/Google_/GoogleGAL_/g' {} +
     if (!class_exists('GoogleGAL_Client')) {
         require_once 'Google/Client.php';
     }
     $client = new GoogleGAL_Client();
     $client->setApplicationName("Wordpress Site");
     $client->setClientId($options['ga_clientid']);
     $client->setClientSecret($options['ga_clientsecret']);
     $client->setRedirectUri($this->get_login_url());
     $scopes = array_unique(apply_filters('gal_gather_scopes', $this->get_default_scopes()));
     $client->setScopes($scopes);
     $client->setApprovalPrompt($options['ga_force_permissions'] ? 'force' : 'auto');
     $oauthservice = null;
     if ($includeoauth) {
         if (!class_exists('GoogleGAL_Service_Oauth2')) {
             require_once 'Google/Service/Oauth2.php';
         }
         $oauthservice = new GoogleGAL_Service_Oauth2($client);
     }
     return array($client, $oauthservice);
 }
 /**
  * Decode an HTTP Response.
  * @static
  * @throws GoogleGAL_Service_Exception
  * @param GoogleGAL_Http_Request $response The http response to be decoded.
  * @param GoogleGAL_Client $client
  * @return mixed|null
  */
 public static function decodeHttpResponse($response, GoogleGAL_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 GoogleGAL_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 GoogleGAL_Service_Exception($error);
         }
         if ($response->getExpectedClass()) {
             $class = $response->getExpectedClass();
             $decoded = new $class($decoded);
         }
     }
     return $decoded;
 }
 private function getResumeUri()
 {
     $result = null;
     $body = $this->request->getPostBody();
     if ($body) {
         $headers = array('content-type' => 'application/json; charset=UTF-8', 'content-length' => GoogleGAL_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 GoogleGAL_Exception("Failed to start the resumable upload");
 }
 public function get_Google_Client()
 {
     $this->setIncludePath();
     if (!class_exists('GoogleGAL_Client')) {
         require_once 'Google/Client.php';
     }
     $client = new GoogleGAL_Client(apply_filters('gal_client_config_ini', null));
     $client->setApplicationName("Wordpress Site");
     return $client;
 }
 /**
  * TODO(ianbarber): This function needs simplifying.
  * @param $name
  * @param $arguments
  * @param $expected_class - optional, the expected class name
  * @return GoogleGAL_Http_Request|expected_class
  * @throws GoogleGAL_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 GoogleGAL_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 GoogleGAL_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 GoogleGAL_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 GoogleGAL_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 = GoogleGAL_Http_REST::createRequestUri($servicePath, $method['path'], $parameters);
     $httpRequest = new GoogleGAL_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 GoogleGAL_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);
 }
Example #11
0
 public function __construct(GoogleGAL_Client $client)
 {
     $this->path = $client->getClassConfig($this, 'directory');
 }
Example #12
0
 /**
  * Executes a GoogleGAL_Http_Request
  *
  * @param GoogleGAL_Client $client
  * @param GoogleGAL_Http_Request $req
  * @return array decoded result
  * @throws GoogleGAL_Service_Exception on server side error (ie: not authenticated,
  *  invalid or malformed post body, invalid url)
  */
 public static function execute(GoogleGAL_Client $client, GoogleGAL_Http_Request $req)
 {
     $httpRequest = $client->getIo()->makeRequest($req);
     $httpRequest->setExpectedClass($req->getExpectedClass());
     return self::decodeHttpResponse($httpRequest);
 }
 /**
  * @param GoogleGAL_Client $client  The current Google client
  */
 public function __construct(GoogleGAL_Client $client)
 {
     $this->setLevel($client->getClassConfig('GoogleGAL_Logger_Abstract', 'level'));
     $format = $client->getClassConfig('GoogleGAL_Logger_Abstract', 'log_format');
     $this->logFormat = $format ? $format : self::DEFAULT_LOG_FORMAT;
     $format = $client->getClassConfig('GoogleGAL_Logger_Abstract', 'date_format');
     $this->dateFormat = $format ? $format : self::DEFAULT_DATE_FORMAT;
     $this->allowNewLines = (bool) $client->getClassConfig('GoogleGAL_Logger_Abstract', 'allow_newlines');
 }