/** * Perform an authenticated api call * * @param string $url * @return Google_Http_Request */ public function call($url) { $request = new Google_Http_Request($url); $this->client->getAuth()->sign($request); return $this->client->getIo()->makeRequest($request); /* @var $response Google_Http_Request */ }
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); $responses[$key] = $response; } catch (Google_Service_Exception $e) { // Store the exception as the response, so succesful responses // can be processed. $responses[$key] = $e; } } } return $responses; } return null; }
public function testSettersGetters() { $client = new Google_Client(); $client->setClientId("client1"); $client->setClientSecret('client1secret'); $client->setState('1'); $client->setApprovalPrompt('force'); $client->setAccessType('offline'); global $apiConfig; $this->assertEquals('client1', $apiConfig['oauth2_client_id']); $this->assertEquals('client1secret', $apiConfig['oauth2_client_secret']); $client->setRedirectUri('localhost'); $client->setApplicationName('me'); $client->setUseObjects(false); $this->assertEquals('object', gettype($client->getAuth())); $this->assertEquals('object', gettype($client->getCache())); $this->assertEquals('object', gettype($client->getIo())); $client->setAuthClass('Google_AuthNone'); $client->setAuthClass('Google_OAuth2'); try { $client->setAccessToken(null); die('Should have thrown an Google_AuthException.'); } catch (Google_AuthException $e) { $this->assertEquals('Could not json decode the token', $e->getMessage()); } $token = json_encode(array('access_token' => 'token')); $client->setAccessToken($token); $this->assertEquals($token, $client->getAccessToken()); }
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); }
public function testExecutorSelection() { $client = $this->getClient(); $this->assertInstanceOf('Google_IO_Curl', $client->getIo()); $config = new Google_Config(); $config->setIoClass('Google_IO_Stream'); $client = new Google_Client($config); $this->assertInstanceOf('Google_IO_Stream', $client->getIo()); }
public function testExecutorSelection() { $default = function_exists('curl_version') ? 'Google_IO_Curl' : 'Google_IO_Stream'; $client = $this->getClient(); $this->assertInstanceOf($default, $client->getIo()); $config = new Google_Config(); $config->setIoClass('Google_IO_Stream'); $client = new Google_Client($config); $this->assertInstanceOf('Google_IO_Stream', $client->getIo()); }
/** * Get crawl issues * * @param $site_url * * @return array */ public function get_crawl_issues() { // Setup crawl error list $crawl_issues = array(); // Issues per page $per_page = 100; $cur_page = 0; // We always have issues on first request $has_more_issues = true; $crawl_issue_manager = new WPSEO_Crawl_Issue_Manager(); $profile_url = $crawl_issue_manager->get_profile(); // Do multiple request while (true === $has_more_issues) { // Set issues to false $has_more_issues = false; // Do request $url = $profile_url . "/crawlissues/?start-index=" . ($per_page * $cur_page + 1) . "&max-results=" . $per_page; $request = new Google_HttpRequest($url); // Get list sites response $response = $this->client->getIo()->authenticatedRequest($request); // Check response code if ('200' == $response->getResponseHttpCode()) { // Create XML object from reponse body $response_xml = simplexml_load_string($response->getResponseBody()); // Check if we got entries if (count($response_xml->entry) > 0) { // Count, future use itemsperpage in Google reponse if (100 == count($response_xml->entry)) { // We have issues $has_more_issues = true; } // Loop foreach ($response_xml->entry as $entry) { $wt = $entry->children('wt', true); $crawl_issues[] = new WPSEO_Crawl_Issue(WPSEO_Redirect_Manager::format_url((string) $wt->url), (string) $wt->{'crawl-type'}, (string) $wt->{'issue-type'}, new DateTime((string) $wt->{'date-detected'}), (string) $wt->{'detail'}, (array) $wt->{'linked-from'}, false); } } } // Up page nr $cur_page++; } return $crawl_issues; }
/** * @param KalturaYoutubeApiDistributionJobProviderData $providerData * @return Google_Client */ protected function initClient(KalturaYoutubeApiDistributionProfile $distributionProfile) { $options = array(CURLOPT_VERBOSE => true, CURLOPT_STDERR => STDOUT, CURLOPT_TIMEOUT => $this->timeout); $client = new Google_Client(); $client->getIo()->setOptions($options); $client->setLogger(new YoutubeApiDistributionEngineLogger($client)); $client->setClientId($distributionProfile->googleClientId); $client->setClientSecret($distributionProfile->googleClientSecret); $client->setAccessToken(str_replace('\\', '', $distributionProfile->googleTokenData)); return $client; }
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"); }
function getGoogleId($access_token) { try { $access_token = json_decode($access_token); $access_token->created = $access_token->issued_at; $access_token->expires = $access_token->expires_at; $access_token = json_encode($access_token); $client = new Google_Client(); $client->setScopes('https://www.googleapis.com/auth/userinfo.profile'); $client->setAccessToken($access_token); $request = new Google_HttpRequest("https://www.googleapis.com/oauth2/v2/userinfo?alt=json"); $userinfo = $client->getIo()->authenticatedRequest($request); $response = json_decode($userinfo->getResponseBody()); return $response->id; } catch (Exception $e) { return null; } }
/** * Returns an instance of Google_Client. Automatically handles set up of the * client, including: * - authentication using configuration in SiteConfig * - caching support via an implementation of the caching interface defined * by the Google API. */ public static function get_client() { $client = new Google_Client(); // If we are going through a proxy, set that up $proxy = static::get_config('external_proxy'); if ($proxy) { $io = $client->getIo(); $parts = static::decode_address($proxy, 'http', '80'); $io->setOptions(array(CURLOPT_PROXY => $parts['Address'], CURLOPT_PROXYPORT => $parts['Port'])); } $client->setClientId(static::get_config('client_id')); $client->setApplicationName(static::get_config('application_name')); // absolute if starts with '/' otherwise relative to site root $keyPathName = static::get_config('private_key_file'); if (substr($keyPathName, 0, 1) !== '/') { $keyPathName = Director::baseFolder() . "/" . $keyPathName; } $client->setAssertionCredentials(new Google_Auth_AssertionCredentials(static::get_config('service_account'), explode(',', static::get_config('scopes')), file_get_contents($keyPathName))); $client->setAccessType('offline_access'); // Set up custom database cache handler. $client->setCache(new GoogleAPICacheHandler()); return $client; }
public function bootstrap($access_token = false) { global $updraftplus; if (!empty($this->service) && is_object($this->service) && is_a($this->service, 'Google_Service_Drive')) { return $this->service; } $opts = $this->get_opts(); if (empty($access_token)) { if (empty($opts['token']) || empty($opts['clientid']) || empty($opts['secret'])) { $updraftplus->log('Google Drive: this account is not authorised'); $updraftplus->log('Google Drive: ' . __('Account is not authorized.', 'updraftplus'), 'error', 'googledrivenotauthed'); return new WP_Error('not_authorized', __('Account is not authorized.', 'updraftplus')); } } // $included_paths = explode(PATH_SEPARATOR, get_include_path()); // if (!in_array(UPDRAFTPLUS_DIR.'/includes', $included_paths)) { // set_include_path(UPDRAFTPLUS_DIR.'/includes'.PATH_SEPARATOR.get_include_path()); // } $spl = spl_autoload_functions(); if (is_array($spl)) { // Workaround for Google Drive CDN plugin's autoloader if (in_array('wpbgdc_autoloader', $spl)) { spl_autoload_unregister('wpbgdc_autoloader'); } // http://www.wpdownloadmanager.com/download/google-drive-explorer/ - but also others, since this is the default function name used by the Google SDK if (in_array('google_api_php_client_autoload', $spl)) { spl_autoload_unregister('google_api_php_client_autoload'); } } /* if (!class_exists('Google_Config')) require_once 'Google/Config.php'; if (!class_exists('Google_Client')) require_once 'Google/Client.php'; if (!class_exists('Google_Service_Drive')) require_once 'Google/Service/Drive.php'; if (!class_exists('Google_Http_Request')) require_once 'Google/Http/Request.php'; */ if ((!class_exists('Google_Config') || !class_exists('Google_Client') || !class_exists('Google_Service_Drive') || !class_exists('Google_Http_Request')) && !function_exists('google_api_php_client_autoload_updraftplus')) { require_once UPDRAFTPLUS_DIR . '/includes/Google/autoload.php'; } $config = new Google_Config(); $config->setClassConfig('Google_IO_Abstract', 'request_timeout_seconds', 60); # In our testing, $service->about->get() fails if gzip is not disabled when using the stream wrapper if (!function_exists('curl_version') || !function_exists('curl_exec') || defined('UPDRAFTPLUS_GOOGLEDRIVE_DISABLEGZIP') && UPDRAFTPLUS_GOOGLEDRIVE_DISABLEGZIP) { $config->setClassConfig('Google_Http_Request', 'disable_gzip', true); } $client = new Google_Client($config); $client->setClientId($opts['clientid']); $client->setClientSecret($opts['secret']); // $client->setUseObjects(true); if (empty($access_token)) { $access_token = $this->access_token($opts['token'], $opts['clientid'], $opts['secret']); } // Do we have an access token? if (empty($access_token) || is_wp_error($access_token)) { $updraftplus->log('ERROR: Have not yet obtained an access token from Google (has the user authorised?)'); $updraftplus->log(__('Have not yet obtained an access token from Google - you need to authorise or re-authorise your connection to Google Drive.', 'updraftplus'), 'error'); return $access_token; } $client->setAccessToken(json_encode(array('access_token' => $access_token, 'refresh_token' => $opts['token']))); $io = $client->getIo(); $setopts = array(); if (is_a($io, 'Google_IO_Curl')) { $setopts[CURLOPT_SSL_VERIFYPEER] = UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify') ? false : true; if (!UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts')) { $setopts[CURLOPT_CAINFO] = UPDRAFTPLUS_DIR . '/includes/cacert.pem'; } // Raise the timeout from the default of 15 $setopts[CURLOPT_TIMEOUT] = 60; $setopts[CURLOPT_CONNECTTIMEOUT] = 15; if (defined('UPDRAFTPLUS_IPV4_ONLY') && UPDRAFTPLUS_IPV4_ONLY) { $setopts[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4; } } elseif (is_a($io, 'Google_IO_Stream')) { $setopts['timeout'] = 60; # We had to modify the SDK to support this # https://wiki.php.net/rfc/tls-peer-verification - before PHP 5.6, there is no default CA file if (!UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts') || version_compare(PHP_VERSION, '5.6.0', '<')) { $setopts['cafile'] = UPDRAFTPLUS_DIR . '/includes/cacert.pem'; } if (UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify')) { $setopts['disable_verify_peer'] = true; } } $io->setOptions($setopts); $service = new Google_Service_Drive($client); $this->client = $client; $this->service = $service; try { # Get the folder name, if not previously known (this is for the legacy situation where an id, not a name, was stored) if (!empty($opts['parentid']) && (!is_array($opts['parentid']) || empty($opts['parentid']['name']))) { $rootid = $this->root_id(); $title = ''; $parentid = is_array($opts['parentid']) ? $opts['parentid']['id'] : $opts['parentid']; while (!empty($parentid) && $parentid != $rootid) { $resource = $service->files->get($parentid); $title = $title ? $resource->getTitle() . '/' . $title : $resource->getTitle(); $parents = $resource->getParents(); if (is_array($parents) && count($parents) > 0) { $parent = array_shift($parents); $parentid = is_a($parent, 'Google_Service_Drive_ParentReference') ? $parent->getId() : false; } else { $parentid = false; } } if (!empty($title)) { $opts['parentid'] = array('id' => is_array($opts['parentid']) ? $opts['parentid']['id'] : $opts['parentid'], 'name' => $title); UpdraftPlus_Options::update_updraft_option('updraft_googledrive', $opts); } } } catch (Exception $e) { $updraftplus->log("Google Drive: failed to obtain name of parent folder: " . $e->getMessage() . ' (line: ' . $e->getLine() . ', file: ' . $e->getFile() . ')'); } return $this->service; }
/** * @requires extension Memcached */ public function testAppEngineAutoConfig() { $_SERVER['SERVER_SOFTWARE'] = 'Google App Engine'; $client = new Google_Client(); $this->assertInstanceOf('Google_Cache_Memcache', $client->getCache()); $this->assertInstanceOf('Google_Io_Stream', $client->getIo()); unset($_SERVER['SERVER_SOFTWARE']); }
// $downloadUrl = "https://spreadsheets.google.com/feeds/spreadsheets/private/full"; // $downloadUrl = "https://spreadsheets.google.com/feeds/worksheets/1SIPGtSxYsYkhqvVQH16bodvOUOEBo_lOb2SzWiQtmlk/private/full"; $downloadUrl = "https://spreadsheets.google.com/feeds/list/1SIPGtSxYsYkhqvVQH16bodvOUOEBo_lOb2SzWiQtmlk/ohvz28m/private/full"; /*Test sheet*/ // $downloadUrl = "https://spreadsheets.google.com/feeds/worksheets/10HtRyp_u2EO5X6yF5l3VR9EVA9IztrlCJY0oQ5YQBJ8/private/full"; // $downloadUrl = "https://spreadsheets.google.com/feeds/worksheets/10HtRyp_u2EO5X6yF5l3VR9EVA9IztrlCJY0oQ5YQBJ8/private/full/od6"; // $downloadUrl = "https://spreadsheets.google.com/feeds/list/10HtRyp_u2EO5X6yF5l3VR9EVA9IztrlCJY0oQ5YQBJ8/od6/private/full"; print "downloadUrl: " . $downloadUrl; if ($downloadUrl) { $request = new Google_Http_Request($downloadUrl, 'GET', null, null); // $httpRequest = Google_Client::$io->authenticatedRequest($request); // var_dump($client->getAuth()); echo "<hr>"; $SignhttpRequest = $client->getAuth()->sign($request); // var_dump($SignhttpRequest); $httpRequest = $client->getIo()->makeRequest($SignhttpRequest); if ($httpRequest->getResponseHttpCode() == 200) { // var_dump($httpRequest); echo "<h1>URA</h1>"; $feed = new SimpleXMLElement($httpRequest->getResponseBody()); // var_dump($httpRequest->getResponseBody()); foreach ($feed->entry as $entry) { // foreach ($item->children() as $child) { // echo $child['name'] ."\n"; // } echo '<p>' . $entry->title . '</p>'; echo '<p>' . $entry->content[0] . '</p>'; // var_dump($entry->content); } } else { echo "<hr>";
/** * 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 execute(Google_Client $client, Google_Http_Request $req) { $httpRequest = $client->getIo()->makeRequest($req); $httpRequest->setExpectedClass($req->getExpectedClass()); return self::decodeHttpResponse($httpRequest, $client); }
$bucket = "my_bucket"; $file_name = "test.txt"; $file_content = "01101010 01110101 01110011 01110100 00100000 01100001 00100000 01110100 01100101 01110011 01110100"; $auth = new Google_Auth_AssertionCredentials($serviceAccount, array('https://www.googleapis.com/auth/devstorage.read_write'), file_get_contents($key_file)); $client = new Google_Client(); $client->setAssertionCredentials($auth); $storageService = new Google_Service_Storage($client); /*** * Write file to Google Storage */ try { $postbody = array('name' => $file_name, 'data' => $file_content, 'uploadType' => "media"); $gsso = new Google_Service_Storage_StorageObject(); $gsso->setName($file_name); $result = $storageService->objects->insert($bucket, $gsso, $postbody); print_r($result); } catch (Exception $e) { print $e->getMessage(); } /*** * Read file from Google Storage */ try { $object = $storageService->objects->get($bucket, $file_name); $request = new Google_Http_Request($object['mediaLink'], 'GET'); $signed_request = $client->getAuth()->sign($request); $http_request = $client->getIo()->makeRequest($signed_request); echo $http_request->getResponseBody(); } catch (Exception $e) { print $e->getMessage(); }
* Migrates you-tube distribution-profiles to use numeric category ID */ require_once __DIR__ . '/../../bootstrap.php'; require_once KALTURA_ROOT_PATH . '/vendor/google-api-php-client-1.1.2/src/Google/autoload.php'; $partnerId = null; if (isset($argv[1]) && is_numeric($argv[1])) { $partnerId = intval($argv[1]); } $oldCategories = array('Film' => 'Film & Animation', 'Autos' => 'Autos & Vehicles', 'Music' => 'Music', 'Animals' => 'Pets & Animals', 'Sports' => 'Sports', 'Travel' => 'Travel & Events', 'Games' => 'Gaming', 'Comedy' => 'Comedy', 'People' => 'People & Blogs', 'News' => 'News & Politics', 'Entertainment' => 'Entertainment', 'Education' => 'Education', 'Howto' => 'Howto & Style', 'Nonprofit' => 'Nonprofits & Activism', 'Tech' => 'Science & Technology'); $appId = YoutubeApiDistributionPlugin::GOOGLE_APP_ID; $authConfig = kConf::get($appId, 'google_auth', null); $googleClientId = isset($authConfig['clientId']) ? $authConfig['clientId'] : null; $googleClientSecret = isset($authConfig['clientSecret']) ? $authConfig['clientSecret'] : null; $options = array(CURLOPT_VERBOSE => true, CURLOPT_STDERR => STDOUT); $client = new Google_Client(); $client->getIo()->setOptions($options); $client->setClientId($googleClientId); $client->setClientSecret($googleClientSecret); $distributionProvider = YoutubeApiDistributionPlugin::getDistributionProviderTypeCoreValue(YoutubeApiDistributionProviderType::YOUTUBE_API); $criteria = new Criteria(); $criteria->add(DistributionProfilePeer::STATUS, DistributionProfileStatus::DELETED, Criteria::NOT_EQUAL); $criteria->add(DistributionProfilePeer::PROVIDER_TYPE, $distributionProvider); if ($partnerId) { $criteria->add(DistributionProfilePeer::PARTNER_ID, $partnerId); } $criteria->addAscendingOrderByColumn(DistributionProfilePeer::ID); $criteria->setLimit(100); $demoCategories = null; $distributionProfiles = DistributionProfilePeer::doSelect($criteria); while ($distributionProfiles) { $lastId = 0;
public function do_bootstrap($opts, $connect) { global $updraftplus; if (!empty($this->service) && is_object($this->service) && is_a($this->service, 'Google_Service_Storage')) { return $this->service; } if (empty($opts)) { $opts = $this->get_opts(); } if (empty($opts['token']) || empty($opts['clientid']) || empty($opts['secret'])) { $updraftplus->log('Google Cloud: this account is not authorised'); $updraftplus->log('Google Cloud: ' . __('Account is not authorized.', 'updraftplus'), 'error', 'googlecloudnotauthed'); return new WP_Error('not_authorized', __('Account is not authorized.', 'updraftplus')); } $access_token = $this->access_token($opts['token'], $opts['clientid'], $opts['secret']); $spl = spl_autoload_functions(); if (is_array($spl)) { // Workaround for Google Cloud CDN plugin's autoloader if (in_array('wpbgdc_autoloader', $spl)) { spl_autoload_unregister('wpbgdc_autoloader'); } // http://www.wpdownloadmanager.com/download/google-drive-explorer/ - but also others, since this is the default function name used by the Google SDK if (in_array('google_api_php_client_autoload', $spl)) { spl_autoload_unregister('google_api_php_client_autoload'); } } if ((!class_exists('Google_Config') || !class_exists('Google_Client') || !class_exists('Google_Service_Storage') || !class_exists('Google_Http_Request')) && !function_exists('google_api_php_client_autoload_updraftplus')) { require_once UPDRAFTPLUS_DIR . '/includes/Google/autoload.php'; } $config = new Google_Config(); $config->setClassConfig('Google_IO_Abstract', 'request_timeout_seconds', 60); # In our testing, $service->about->get() fails if gzip is not disabled when using the stream wrapper if (!function_exists('curl_version') || !function_exists('curl_exec') || defined('UPDRAFTPLUS_GOOGLECLOUD_DISABLEGZIP') && UPDRAFTPLUS_GOOGLECLOUD_DISABLEGZIP) { $config->setClassConfig('Google_Http_Request', 'disable_gzip', true); } $client = new Google_Client($config); $client->setClientId($opts['clientid']); $client->setClientSecret($opts['secret']); $client->setApplicationName("UpdraftPlus WordPress Backups"); $client->setRedirectUri($this->redirect_uri()); $client->setScopes('https://www.googleapis.com/auth/devstorage.full_control'); // Do we have an access token? if (empty($access_token) || is_wp_error($access_token)) { $updraftplus->log('ERROR: Have not yet obtained an access token from Google (has the user authorised?)'); $updraftplus->log(__('Have not yet obtained an access token from Google - you need to authorise or re-authorise your connection to Google Cloud.', 'updraftplus'), 'error'); return $access_token; } $client->setAccessToken(json_encode(array('access_token' => $access_token, 'refresh_token' => $opts['token']))); $io = $client->getIo(); $setopts = array(); $ssl_disableverify = isset($opts['ssl_disableverify']) ? $opts['ssl_disableverify'] : UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify'); $ssl_useservercerts = isset($opts['ssl_useservercerts']) ? $opts['ssl_useservercerts'] : UpdraftPlus_Options::get_updraft_option('updraft_ssl_useservercerts'); if (is_a($io, 'Google_IO_Curl')) { $setopts[CURLOPT_SSL_VERIFYPEER] = $ssl_disableverify ? false : true; if (!$ssl_useservercerts) { $setopts[CURLOPT_CAINFO] = UPDRAFTPLUS_DIR . '/includes/cacert.pem'; } // Raise the timeout from the default of 15 $setopts[CURLOPT_TIMEOUT] = 60; $setopts[CURLOPT_CONNECTTIMEOUT] = 15; if (defined('UPDRAFTPLUS_IPV4_ONLY') && UPDRAFTPLUS_IPV4_ONLY) { $setopts[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4; } } elseif (is_a($io, 'Google_IO_Stream')) { $setopts['timeout'] = 60; # We had to modify the SDK to support this # https://wiki.php.net/rfc/tls-peer-verification - before PHP 5.6, there is no default CA file if (!$ssl_useservercerts || version_compare(PHP_VERSION, '5.6.0', '<')) { $setopts['cafile'] = UPDRAFTPLUS_DIR . '/includes/cacert.pem'; } if ($ssl_disableverify) { $setopts['disable_verify_peer'] = true; } } $io->setOptions($setopts); $service = new Google_Service_Storage($client); $this->client = $client; $this->service = $service; return $this->service; }
} // initialize the drive service with the client. $service = new Google_DriveService($client); /** * Gets the metadata and contents for the given file_id. */ $app->get('/svc', function () use($app, $client, $service) { checkUserAuthentication($app); checkRequiredQueryParams($app, array('file_id')); $fileId = $app->request()->get('file_id'); try { // Retrieve metadata for the file specified by $fileId. $file = $service->files->get($fileId); // Get the contents of the file. $request = new Google_HttpRequest($file->downloadUrl); $response = $client->getIo()->authenticatedRequest($request); $file->content = $response->getResponseBody(); renderJson($app, $file); } catch (Exception $ex) { renderEx($app, $ex); } }); /** * Creates a new file with the metadata and contents * in the request body. Requires login. */ $app->post('/svc', function () use($app, $client, $service) { checkUserAuthentication($app); $inputFile = json_decode($app->request()->getBody()); try { $file = new Google_DriveFile();
<?php require 'vendor/autoload.php'; session_start(); $client = new Google_Client(); $client->setAuthConfigFile("http://localhost/configuration/name/google-credentials.json"); $client->addScope("https://www.googleapis.com/auth/userinfo.profile"); $client->addScope("https://www.googleapis.com/auth/userinfo.email"); $client->setAccessType('offline'); $client->setApprovalPrompt('auto'); $client->setRedirectUri('postmessage'); if (function_exists('setProxy')) { $client->getIo()->setOptions(array(CURLOPT_PROXY => 'localhost', CURLOPT_PROXYPORT => 8888)); } if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { include_once 'php/name.php'; $client->setAccessToken($_SESSION['access_token']); try { if (!isset($_SESSION['token_data'])) { $token_data = $client->verifyIdToken()->getAttributes(); if ($token_data["payload"]["email_verified"]) { $_SESSION['token_data'] = $token_data; } } $_SESSION['canVote'] = checkVotingRights($_SESSION["token_data"]["payload"]["email"]); $oAuth2 = new \Google_Service_Oauth2($client); $oAttr = $oAuth2->userinfo->get(); } catch (Exception $e) { unset($_SESSION['access_token']); $redirect_uri = $_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER['HTTP_HOST']; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
// $client->setRedirectUri('insert_your_redirect_uri'); // $client->setDeveloperKey('insert_your_developer_key'); if (isset($_GET['code'])) { $client->authenticate(); $_SESSION['token'] = $client->getAccessToken(); $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } if (isset($_REQUEST['logout'])) { unset($_SESSION['token']); $client->revokeToken(); } if ($client->getAccessToken()) { $req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full"); $val = $client->getIo()->authenticatedRequest($req); // The contacts api only returns XML responses. $response = json_encode(simplexml_load_string($val->getResponseBody())); print "<pre>" . print_r(json_decode($response, true), true) . "</pre>"; // The access token may have been updated lazily. $_SESSION['token'] = $client->getAccessToken(); } else { $auth = $client->createAuthUrl(); } if (isset($auth)) { print "<a class=login href='{$auth}'>Connect Me!</a>"; } else { print "<a class=logout href='?logout'>Logout</a>"; }