Giter Club home page Giter Club logo

google-api-php-client's People

Contributors

abusalam avatar assimilationstheorie avatar bshaffer avatar carusogabriel avatar chixor avatar deconf avatar dwsupplee avatar grant avatar ianbarber avatar ip512 avatar ircmaxell avatar ithinkihaveacat avatar itsazzad avatar jdpedrie avatar justinbeckwith avatar kunit avatar localheinz avatar ltrebing avatar mattwhisenhunt avatar mishan avatar release-please[bot] avatar ricardofontanelli avatar silvolu avatar simonschaufi avatar sqrrrl avatar swissspidy avatar tbetbetbe avatar theacodes avatar whatthejeff avatar wibblymat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-api-php-client's Issues

0.6->1.0 migration guide incomplete

Hi, folks. I just submitted a patch for OwnCloud's Google Drive plugin to migrate it to 1.0 (there's a small chance I even got it right!), and noticed a couple of things missing from the 0.6-1.0 migration guide:

  • In Client.php , $auth , $io , $cache and $config are now private; it seems to have been pretty common for people to use $io especially when downloading files, and indeed Google's own sample code at https://developers.google.com/drive/web/manage-downloads does this. Would be good to note that you have to use getAuth(), getIo(), getCache(), getConfig() now.
  • The authenticatedRequest functions seem to have moved from the IO classes to the Auth classes

So with those two taken together, in migrating the OC app's file download function, I had to go from:

$io->authenticatedRequest($request);

to:

getAuth()->authenticatedRequest($request);

Thanks!

Simple File Upload not working

I was trying to upload a simple file to drive using the files->insert API.
Just migrated from .6 to 1.0 but still didn't work out.

Can anyone please help?


Warning: file_get_contents(compress.zlib://https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&key=xxxxxxxxxxxxxx): failed to open stream: operation failed in /Applications/XAMPP/xamppfiles/htdocs/Google/IO/Stream.php on line 115

Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect' in /Applications/XAMPP/xamppfiles/htdocs/Google/IO/Stream.php:118 Stack trace:
#0 /Applications/XAMPP/xamppfiles/htdocs/Google/Http/REST.php(42): Google_IO_Stream->makeRequest(Object(Google_Http_Request))
#1 /Applications/XAMPP/xamppfiles/htdocs/Google/Client.php(487): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /Applications/XAMPP/xamppfiles/htdocs/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /Applications/XAMPP/xamppfiles/htdocs/Google/Service/Drive.php(1694): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 /Applications/XAMPP/xamppfiles/htdocs/dashboard_update.php(59): Google_Service_Drive_Files_Resource->insert(Object(Google_Service_Drive_DriveFile), Array)
#5 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/Google/IO/Stream.php on line 118

allow gzip for API calls

The documentation recommends using gzip for API calls, but it doesn't look like the php-client is doing this. I thought maybe the Google_Service or Google_Service_Resource classes would be able to customize the headers of the Google_Http_Request object they ultimately call, but there didn't seem to be a way to do that.

Thanks for listening!

Return HTTP Code in Media File Upload

It seems like it should be easier to get the HTTP Response Code from MediaFileUpload.php, so if there is an error it can be retried.

For example declaring a variable
/** @var int $httpResultCode */
private $httpResultCode;

adding the function

public function getHttpResultCode()
{
    return $this->httpResultCode;
}

and setting

$code = $response->getResponseHttpCode();

$this->httpResultCode = $code;

in the nextChunk function

Another related question - if I am using the upload example from https://github.com/google/google-api-php-client/blob/master/examples/fileupload.php - and I am looping through, checking for errors would $status = $media->nextChunk(false); just try uploading the last chunk that was set in nextChunk again?

Cannot authenticate

I've been trying to follow the examples on the google group and in this repository.

I'm building this on localhost have the following topography:

webRoot/
  api/
    index.php
    resources/calendar.php

  libs/google/1.0.1a/
    Auth/
    Cache/
    Http/
    …
    Client.php
    …

The contents of libs/google/1.0.1a/ are from src/Google/ (and require_once links updated via global find+replace).

curl -X GET 'http://localhost/api/index.php/calendar/not_used_yet/events'

index.php detects calendar in the path and forwards the request to calendar.php:

# api/resources/calendar.php
session_start();
class Calendar extends Response {
  protected $service;

  function __construct() {
    set_include_path(get_include_path() . PATH_SEPARATOR . 'libs/google/1.0.1a/');
    require_once 'Client.php';
    require_once 'service/Calendar.php';

    $client = new Google_Client();
    $client->setApplicationName('test');
    // redirectUri = 'http://localhost/api/index.php/calendar'
    $client->setScopes('calendar');

    $this->service = new Google_Service_Calendar($client);

    if ( isset($_GET['code']) )
    {
      $client->authenticate($_GET['code']);
      $_SESSION['access_token'] = $client->getAccessToken();
    }
    if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
      $client->setAccessToken($_SESSION['access_token']);
    else
      $authUrl = $client->createAuthUrl();

    if ( $client->getAccessToken() )
    {
      $_SESSION['access_token'] = $client->getAccessToken();
      $token_data = $client->verifyIdToken()->getAttributes();
    }
  }

  public function events( $req ) {
    $this->connect();
    $calendarList = $this->service->calendarList->listCalendarList();
  }
}

I've populated the params in Config.php, yet I still get:

Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList?key=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$: (401) Login Required' in sitRoot/api/libs/google/1.0.1a/Http/REST.php:75 Stack trace:

0 sitRoot/api/libs/google/1.0.1a/Http/REST.php(45): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))

1 sitRoot/api/libs/google/1.0.1a/Client.php(492): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))

2 sitRoot/api/libs/google/1.0.1a/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))

3 sitRoot/api/libs/google/1.0.1a/service/Calendar.php(941): Google_Service_Resource->call('list', Array, 'Google_Service_...')

4 /Sites/ in sitRoot/api/libs/google/1.0.1a/Http/REST.php on line 75

I also can't get idtoken.php to work:

Invalid parameter value for redirect_uri: Raw IP addresses not allowed.

If an IP address is not allowed, then why did the api console ask for one when generating my server token??

Also, this is an API. Why is there a redirect? There is no human interaction—my script is providing credentials; how is this not a call and response?

Problem inserting rows Fusiontable

Hello, I have a problem when I want to insert a row into kml type column (text > 650 characters) .

$local_kml="&ltMultiGeometry&gt&ltPoint&gt&ltcoordinates&gt24.140480,44.135342,0.0&lt/coordinates&gt&lt/Point&gt&ltLineString&gt&ltextrude&gt1&lt/extrude&gt&lttessellate&gt1&lt/tessellate&gt&ltcoordinates&gt24.140480,44.135342,0.0 24.126301,44.144180,0.0 24.115210,44.151180,0.0 24.114630,44.151489,0.0 24.114120,44.151699,0.0 24.112841,44.152069,0.0 24.107710,44.153358,0.0 24.105780,44.153809,0.0 24.102489,44.154678,0.0 24.101170,44.155102,0.0 24.100401,44.155399,0.0 24.097790,44.156681,0.0 24.097340,44.156818,0.0 24.095270,44.157291,0.0 24.094919,44.157410,0.0 24.090691,44.159679,0.0 24.087879,44.160992,0.0 24.085251,44.161980,0.0 24.080259,44.163780,0.0 24.054230,44.172298,0.0 24.042780,44.176102,0.0 &lt/coordinates&gt&lt/LineString&gt&lt/MultiGeometry&gt";
$insertQuery = "insert into 1_in5SzLPuEV-MnS_Eq1vf2D4ICJJI4wR7bQ5hOo (kml,dn,km_start,km_end,text,iconName,lastUpdate) values ('{$local_kml}','test4','{$km_start }','{$km_end}','{$cauza}','{$snowflake_simple}',1)";
$ftclient=ConnectFusion($client);
var_dump($ftclient->query->sql($insertQuery));

Warning: file_get_contents(compress.zlib://https://www.googleapis.com/fusiontables/v1/query): failed to open stream: operation failed in .../Google/IO/Stream.php on line 115

Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect' in .../Google/IO/Stream.php:118 Stack trace: #0 .../Google/Http/REST.php(42): Google_IO_Stream->makeRequest(Object(Google_Http_Request)) #1 .../Google/Client.php(487): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request)) #2 .../Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request)) #3 /.../Google/Service/Fusiontables.php(682): Google_Service_Resource->call('sql', Array, 'Google_Service_...') #4 /../my.php(113): Google_Service_Fusiontables_Query_Resource->sql('insert into 1_i...') #5 .../my.php(59): test(Object(Google_ in ../Google/IO/Stream.php on line 118

It works if I remove some coordonates from $local_kml.

allowed memory fatal error

PHP Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 36 bytes) in /vendor/google/apiclient/src/Google/Model.php on line 113

this error keep shown even increasing the php.ini allowed memory

Stream.php Error

I get an error when uploading a video to YouTube.
This script is being run in a command line, after the form is submitted.

Code:

// Get the Google Client.
require_once MODULES.'Social'.DS.'Google'.DS.'Client.php';
// Get the YouTube Service.
require_once MODULES.'Social'.DS.'Google'.DS.'Service'.DS.'YouTube.php';

$client=new Google_Client();
$client->setApplicationName("API Project");
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setRedirectUri(REDIRECT_URI);
$client->setDeveloperKey(DEV_KEY);
$client->refreshToken(REFRESH_TOKEN);

$youtube_service=new Google_Service_YouTube($client);

// Lots of code snipping here

// Set the path to the video on the server.
$video_path='video_file.mp4';

// Create a YouTube video with snippet and status.
$google_video=new Google_Service_YouTube_Video();
$google_video->setSnippet($google_video_snippet);
$google_video->setStatus($google_video_status);

// Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks, for reliable connections).
// Setting it lower leads better recovery (fine-grained chunks).
$chunk_size_bytes=1_1024_1024;

// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(TRUE);

// Create a video insert request.
$insert_response=$yt->insertVideo('status,snippet', $google_video);

// Create a MediaFileUpload object for resumable uploads.
$media_file_upload=new Google_Http_MediaFileUpload($client, $insert_response, 'video/*', NULL, TRUE, $chunk_size_bytes);
$media_file_upload->setFileSize(filesize($video_path));

// Set $upload_status to FALSE by default.
$upload_status=FALSE;
// Read the media file and upload it chunk by chunk.
$handle=fopen($video_path, "rb");
while(!$upload_status && !feof($handle))
{
$chunk=fread($handle, $chunk_size_bytes);
$upload_status=$media_file_upload->nextChunk($chunk);
}
fclose($handle);

// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(FALSE);

Error:

Warning: file_get_contents(/upload/youtube/v3/videos?part=status%2Csnippet&key=BLAH_BLAH&uploadType=resumable) [/phpmanual/function.file-get-contents.html]: failed to open stream: No such file or directory in Google/IO/Stream.php on line 109

Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect' in Google/IO/Stream.php:112
Stack trace:
#0 Google/Http/MediaFileUpload.php(260): Google_IO_Stream->makeRequest(Object(Google_Http_Request))
#1 Google/Http/MediaFileUpload.php(123): Google_Http_MediaFileUpload->getResumeUri()
#2 YouTubeUpload.php(118): Google_Http_MediaFileUpload->nextChunk('????ftypmp42???...')
#3 {main}

thrown in Google/IO/Stream.php on line 112

dataTable property not accessible

This property is protected and there is no method to get the dataTable data.

Outputs a dataTable property in the response, containing a Data Table object. This Data Table object can be used directly with Google Charts visualizations.

So how can I use this "directly" with Google Charts API?

File cache locking issue

Trying to get a google+ sign in working, I ran across an issue where the file cache was failing to write any data into the cache file, giving a warning such as:

Warning: file_put_contents(): Only 0 of 5610 bytes written, possibly out of free disk space in D:\Web\igorally\site\vendor\google\apiclient\src\Google\Cache\File.php line 73

Spent a while messing with permissions figuring that was the cause, but when I dived into the code I saw the issue was caused by the file locking setup.

Locking the file using fopen/flock prevents file_put_contents from writing to that same file. Changing the line to fwrite resolved the problem.

$result = file_put_contents($storageFile, $data);

changed to

$result = fwrite($this->fh, $data);

Possible small bug on Oauth2.php

Hello there,

On this line 156, file "OAuth2.php":
https://github.com/google/google-api-php-client/blob/5c58413bba2301ef602d2a6650d4f5d82088ce64/src/Google/Auth/OAuth2.php#L156

It’s:

if (strpos($scope, 'plus.login') && strlen($rva) > 0) {

And should be:

if (strpos($scope, 'plus.login')!==false && strlen($rva) > 0) {

We also need a solution for issue 39, because the third example on https://developers.google.com/youtube/partner/code_samples/php#uploading_a_new_reference__so_youtube_can_automatically_generate_claims_for_newly_uploaded_videos_on_behalf_of_the_asset_s_owner isn’t working… Even if you put the YouTubePartner.php file to work along with the code, because this file isn’t on the repository yet.

Could you please have a look at it?

Best regards,

require_once error in Client.php

I am trying to migrate to 1.0 api in Drupal 7.and the first error I get is:

Fatal error: require_once() [function.require]: Failed opening required 'Google/Auth/AssertionCredentials.php' (include_path='.;C:\Program Files (x86)\acquia-drupal\common\pear') in C:\Users\cdavidyoung\Sites\public_html\includes\google-api-php-client\src\Google\Client.php on line 18

Why are all of the paths now prefixed with "Google/"? This seems to be causing the error. Is there include_path setting that we need to set to use this new api?

createAuthUrl() may be configured to return a URL with HTML-encoded ampersands, but Google Drive's auth fails on such URLs

So, this is an interesting one. Still working on porting OwnCloud's Google Drive app to the v1.x version of google-api-php-client .

0.6's (OAuth2) createAuthUrl didn't use http_build_query, it just imploded an array into a string using a raw & character as a separator:

$params = implode('&', $params);

1.0's version uses http_build_query:

    return self::OAUTH2_AUTH_URL . "?" . http_build_query($params);

On modern PHP versions (it seems to be 5.3+), http_build_query uses an encoded ampersand as the separator by default. So createAuthUrl gives a URL like this:

"https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=https%3A%2F%2Fwww.happyassassin.net%2Fowncloud%2Findex.php%2Fsettings%2Fadmin&client_id=redacted.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&access_type=online&approval_prompt=auto"

However, the actual OAuth system doesn't seem to like that. If we pass it that URL, we get this:

Error:invalid_request

Missing required parameter: redirect_uri

Request Details

response_type=code
amp;redirect_uri=https://www.happyassassin.net/owncloud/index.php/settings/admin
amp;scope=https://www.googleapis.com/auth/drive
amp;approval_prompt=auto
amp;access_type=online
amp;client_id=(redacted)

Note all those "amp;"s.

If I make OwnCloud's app do an html_entity_decode() on the URL returned by createAuthUrl() then everything works, but this is obviously fairly silly.

If I'm understanding everything correctly, then either Google's OAuth implementation should be made to work correctly with HTML-encoded ampersands, or google-api-php-client should be doing this:

return self::OAUTH2_AUTH_URL . "?" . http_build_query($params, '', '&');

I'm fairly sure the problem here is on Google's side either in google-api-php-client or in your OAuth server, I don't think the OC app is doing anything wrong.

Possible cache issue...?

Old subject: is it possible 'if-none-match' breaks file_get_contents in IO\Stream.php?

Hi... I've just updated "google/apiclient" and my code stopped to work. After a while I've found a possible issue... Double quotes in etag for if-none-match header are not escaped. Is this important?

When I've added a line ($v = addslashes($v);) just before line 77 everything is back to normal... I think...
...

YouTubePartner.php not found

Hello

We here at Altafonte Music Network are trying to connect our automated system with your APIs. We’re working with Google API YoutubePartners.

Our main goal is to upload audio references to match and automatically claim videos. We work ok PHP.

We’re following this example:
https://developers.google.com/youtube/partner/code_samples/php#uploading_a_new_reference__so_youtube_can_automatically_generate_claims_for_newly_uploaded_videos_on_behalf_of_the_asset_s_owner
(second half of the doc)

We got it through the old API (Google API PHP Client 0.6.7) and the "Google_YouTubePartnerService.php" file we found here: https://developers.google.com/youtube/partner/client_libraries , but this isn’t useful because we need “Service account” authentication, and the API doesn’t work with this.

So, we tried with Google API PHP Client 1.0.0 unsuccessfully. We get the authentication but we need to find this file: "Google/Service/YouTubePartner.php”, called by your example on the URL mentioned above: https://developers.google.com/youtube/partner/code_samples/php

Thanks for your help!

handling of partially failed batch jobs

If some subset of a batch job fails, then it is not possible to see which requests failed because any one failure will throw an exception that exits Google_Http_Batch::parseResponse. Recovery/reporting would be possible if Google_Http_Batch had an option to include exceptions in its response array and allow the caller to examine/deal with them.

Undefined index: errors in google-api-php-client/src/io/Google_REST.php

sometimes the google+ api retuns errors without setting the 'errors' key. so the code throws an error.

in relation to https://code.google.com/p/google-api-php-client/issues/detail?id=266 i would suggest the following change:

//throw new Google_ServiceException($err, $code, null, $decoded['error']['errors']);
$error_msg = $err;
if(isset($decoded['error']) && isset($decoded['error']['errors'])){
  $error_msg = $decoded['error']['errors'];
}
throw new Google_ServiceException($err, $code, null, $error_msg);

Weird Size Issue - 600KB video file results in 18MB upload traffic. 8 MB file results in 228MB outgoing traffic

I am trying to upload a video to you tube using the latest code samples.
The file size is around 600 KB (KiloBytes).

While the sample uploads the video fine using the chunked upload method, I found something really strange.

A file size of 600KB results in an upload traffic of around 17 to 18 MB.
Assuming, a base64_encode of the same file results in a physical file size of : 884KB.

Can someone explain, if the large upload traffic is natural or there is some issue ?

If it is normal, then this is an extremely inefficient way of uploading data. Youtube should develop better methods.

I also tested with a physical file of size 8MB and it resulted in an upload traffic of whooping 228 MB.

Can any one throw some light on this ? if someone wants, I can paste the entire code of the script I am using,

I can see why people are complaining about slow uploads too : #50

Edit : Tested with the previous version of the code. google-api-php-client-1.0.0-alpha - This works fine, and upload traffic is equal to file size.

Youtube upload video error

Following the example from here https://developers.google.com/youtube/v3/code_samples/php#resumable_uploads I've tried to upload a video but received the next error :

Warning: file_get_contents(/upload/youtube/v3/videos?part=status%2Csnippet&uploadType=resumable): failed to open stream: No error in...\Google\IO\Stream.php on line 109
Call Stack

Time Memory Function Location

1 0.0011 160976 {main}( ) ..\upload.php:0
2 0.0609 3369288 Google_Http_MediaFileUpload->nextChunk( ) ..\upload.php:90
3 0.0609 3369512 Google_Http_MediaFileUpload->getResumeUri( ) ..\MediaFileUpload.php:123
4 0.0615 3370664 Google_IO_Stream->makeRequest( ) ..\MediaFileUpload.php:260
5 0.0618 3375192 file_get_contents ( ) ..\Stream.php:109

Insert object into google cloud storage returns 'no such bucket'

Im using google-api-php-client. I´m authenticating with service account and recieving TOKEN ok. Trying to insert object in Google Cloud Storage, using Google Cloud Storage JSON api.

When trying to INSERT object into BUCKET, returns: NoSuchBucket-The specified bucket does not exist. But I can assure that it does exist, as I can see in the web manager console, and already have images I´ve uploaded days ago.

The complete message says: Error calling POST https://www.googleapis.com/upload/storage/v1beta2/b/{here-goes-my-existing-bucket-name}/o?uploadType=multipart&name=thec36b23baf2778d.jpg: (404)

How may I start debuging to find the issue?

thanks

Store id_token when refreshing token

Is there a reason to not store the id_token when refreshing the access_token?

My question is because when I use the verifyIdToken method after a refreshToken, it fails.

Why PHP 5.2?

I'm just curious, why you still have the requirements set to PHP 5.2?
Why don't you move the codebase to 5.4 in order to leverage the new features as namespaces, autoloading, traits, etc.

Service Account and Delegation of Authority

Hi there,

I spent some hours to try to understand what's wrong but I really do know.
I'm trying to use the Directory service with a Service Account.
I have configure every thing possible as describe here on this page https://developers.google.com/drive/web/delegation#delegate_domain-wide_authority_to_your_service_account :

  • Create a service account on my console API ;
  • Active the API on my Google Apps console ;
  • Add the Client ID with scopes on the Google Apps console ;

But i'm facing a strange issue with the API... (i've try with the master version and also with tags...)

Here is my code :

function newBuildService($anArray) {
    $config = new Google_Config();
    $config->setCacheClass('Google_Cache_Memcache');
    $config->setClassConfig('Google_Cache_Memcache',
      array('host' => 'does_not_matter', 'port' => '37337'));
    /*$config->setClassConfig('Google_Http_Request',
      array('disable_gzip' => false));*/

    global $client;
    $client = new Google_Client($config);
    $client->setApplicationName("Client_Library_Examples");
    $service = new Google_Service_Directory($client);
    $_SESSION['service_token'] = null;
    if (isset($_SESSION['service_token'])) {
      $client->setAccessToken($_SESSION['service_token']);
    }
    $key = file_get_contents($anArray['p12file']);
    $cred = new Google_Auth_AssertionCredentials(
         $anArray['service_account_email'],
        array(DIRECTORY_SCOPE),
        $key
        ,'notasecret'
        ,'http://oauth.net/grant_type/jwt/1.0/bearer'
    );
    ///!\ THIS LINE CAUSE THE ISSUE
    $cred->sub = "[email protected]";

    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {
      $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $_SESSION['service_token'] = $client->getAccessToken();   
    return $service;
}   
$adminService = newBuildService($anArray);
$res = $adminService->groups->listGroups(array('domain'=>'mydomain.com'));

When a run this code, i've this error :
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '<title>Comptes Google</title> <script type="text/javascript" src="https://ssl.gstatic.com/accounts/o/237772143-common_lib.js"></script> <style>@media screen and (max-width:500px) {#robot {background: none; min-height: 0; min-width: 0; padding: 0;}#stack_trace {display: none;}} #oauth2_request_info_header {background-image: url("https://ssl.gstatic.com/accounts/o/blank.gif");}</style>

<a href="//www.google.com/" in D:\workspace_myeclipse10\visu\visu\google-api-php-client-master\src\Google\Auth\OAuth2.php on line 328

And when i try comment this mandatory line "$cred->sub = "[email protected]";" i've this message :
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/admin/directory/v1/groups?domain=mydomain.com: (403) Not Authorized to access this resource/api'

I hope this is clear. Does anyone knows what's wrong ?
Thanks for your help.
Sebastien

Auto-loader doesn't work for service subclasses

When using composer to install this library and depending on the composer autoloader, it is unable to instantiate a service subclass unless you first instantiate the service class.

Example:

<?php
include 'vendor/autoload.php';
$googleUserName = new Google_Service_Directory_UserName();
?>

That results in the error:

include(Google_Service_Directory_User.php): failed to open stream: No such file or directory

The problem is that file does not exist, the class Google_Service_Directory_User is defined in Google/Service/Directory.php.

The sub/child classes of each service should be defined in their own files in the proper folders. So class Google_Service_Directory_User should be defined in Google/Service/Directory/User.php.

As a workaround for now, you must instantiate the service class object first, which causes PHP to load that file, which then includes the definition of the sub class:

<?php
include 'vendor/autoload.php';
$dir = new Google_Service_Directory($client);
$googleUserName = new Google_Service_Directory_UserName();
?>

That way works.

As a side note, if part of the reason for the refactoring of this library is to use more modern practices, it should also ditch the Super_Long_Class_Names in favor of namespaces and up the minimum PHP version.

PHP Notices

Calling:

$sources = $service->management_customDataSources->listManagementCustomDataSources($prop->accountId, $prop->id);
$customDataSources = $sources->getItems();

results in PHP Notices when no items are returned:

PHP Notice:  Undefined index: items in .../vendor/google/apiclient/src/Google/Model.php on line 49
PHP Notice:  Undefined index: items in .../vendor/google/apiclient/src/Google/Model.php on line 70

Temporary files not cleaned up

Came upon an issue where server was degraded by the client using up all the available inodes for temporary file storage.

File upload generating incorrect request URL

When executing examples/simplefileupload.php a fatal Google_IO_Exception of "HTTP Error: Unable to connect" is thrown in Google_IO_Stream::makeRequest() at line 112. This is due to the request URL from Google_Http_Request::getUrl() resulting in a value of "/upload/drive/v2/files?uploadType=media" while I was expecting a fully qualified domain name to be included, such as "https://www.googleapis.com" from Google_Config::getBasePath().

I stepped through the execution and noticed Google_Service_Resource::call() is trying to help out a file upload by creating a new instance of Google_Http_MediaFileUpload. However, Google_Http_MediaFileUpload will set the Google_Http_Request::$baseComponent in Google_Http_MediaFileUpload ::transformToUploadUrl() before Google_Http_REST::execute() gets a chance to set the value at line 44.

Backtrace
6. throw() at /vagrant/src/Google/IO/Stream.php: 112
5. makeRequest() at /vagrant/src/Google/Http/REST.php: 46
4. execute() at /vagrant/src/Google/Client.php: 492
3. execute() at /vagrant/src/Google/Service/Resource.php: 194
2. call() at /vagrant/src/Google/Service/Drive.php: 1696

  1. insert() at /vagrant/examples/simplefileupload.php: 86

listEvents "id" parameter in request

My code looks something like this:

...
$service = new Google_Service_Calendar($client);
$events = $service->events->listEvents('{my_nonurlencoded_calendar}');

This returns:

[09-Dec-2013 06:51:32 UTC] PHP Fatal error:  Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/calendars/{my_calendar}%7Bid%7D?key={my_key}: (404) Not Found'

Note the %7Bid%7D. I scouted around the best I could to try to find where that request parameter is added to no avail.

Typos in Analytics Service

Found an issue using this service recently throwing an error:

Failed with message: (get) unknown parameter: 'start-date'

Turns out there are two typos in the Analytics service file

"start_date" => array(
    "location" => "query",
    "type" => "string",
    'required' => true,
),
"end_date" => array(
    "location" => "query",
    "type" => "string",
    'required' => true,
),

should be

"start-date" => array(
    "location" => "query",
    "type" => "string",
    'required' => true,
),
"end-date" => array(
    "location" => "query",
    "type" => "string",
    'required' => true,
),

Issues with functions using PHP versions prior to 5.3.4

gzip compression for the API client does not work prior to PHP version 5.3.4: The documentation should be updated to note this or a check should be done in the code to disable gzip compression for PHP versions prior to 5.3.4 (at least until cURL support is added)

There is a bug in PHP versions prior to 5.3.4 where the auth headers will not get set properly using stream_context_create, so all requests to the APIs will fail.

See https://bugs.php.net/bug.php?id=52926 and http://www.php.net/ChangeLog-5.php#5.3.4... Something like:

if(version_compare(phpversion(),"5.3.4",">=")){
  $disable_gzip = false;
}else{
  $disable_gzip = true;
}

And then setting the disable_gzip param to that…

Also if 5.2.1 is still being supported, then should lcfirst be used in src/Google/Utils.php? This appears to have been released in 5.3

Google_Service_Oauth2 get user info

I am unable of retrieving authenticated user information through Google_Service_Oauth2. After authentication processes i am able to execute the following method:

$user = $oauth2->userinfo->get();

But when I print user fields by calling getEmail, getGiven_name, getFamily_name and so on, these fields are in blank except for getId. User Id is ok, so the authentication process is correct, but basic profile information is in blank.

I saw that this get method accepts an array of optional parameters, and I have tried to add email, or other fields but it does not work.

With the old 0.6.x library I was able to extract these fields without problems.

Any hint?

Google Tasks - Error calling GET - (401) Login Required

I am trying to get list of tasks and I am getting error Login Required. How can I view my Tasks in default tasklist?

Error:

Fatal error:  Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/tasks/v1/users/@me/lists: (401) Login Required' in C:\wamp\www\tasks\Google\Http\REST.php:75
Stack trace:
#0 C:\wamp\www\tasks\Google\Http\REST.php(45): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 C:\wamp\www\tasks\Google\Http\Request.php(83): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 C:\wamp\www\tasks\Google\Service\Resource.php(190): Google_Http_Request->execute()
#3 C:\wamp\www\tasks\Google\Service\Tasks.php(371): Google_Service_Resource->call('list', Array, 'Google_Service_...')
#4 C:\wamp\www\tasks\index.php(41): Google_Service_Tasks_Tasklists_Resource->listTasklists()
#5 {main}
  thrown in C:\wamp\www\tasks\Google\Http\REST.php on line 75

My code:

<?php
        require_once 'Google/Client.php';
        require_once 'Google/Service/Tasks.php';

        $client_id = 'MY_CLIENT_ID';
        $client_secret = 'MY_CLIENT_SECRET';
        $redirect_uri = 'http://localhost/tasks/';

        $client = new Google_Client();
        $client->setApplicationName("Client_Library_Examples");
        $client->setClientId($client_id);
        $client->setClientSecret($client_secret);
        $client->setRedirectUri($redirect_uri);
        $client->setScopes("https://www.googleapis.com/auth/tasks");
        $client->setScopes("https://www.googleapis.com/auth/tasks.readonly");
        $authUrl = $client->createAuthUrl();

        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
            $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
            header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
        }

        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
            $client->setAccessToken($_SESSION['access_token']);
        }

        echo '<a href="' . $authUrl . '">link me</a>';

        $service = new Google_Service_Tasks($client);

        echo '<pre>';
        $service->tasklists->listTasklists();


        ?>

function does not work -> management_dailyUploads (Analytics Daily Upload)

Analytics Management API - Daily Upload Developer Guide

such a request causes an error:
$Analytics_test = $service->management_dailyUploads->upload(
'123456789', // your accountID
'UA-123456789-1', // your web property ID
'xxxxxxxxxxxxxxxxxx', // your custom data source UID
'2014-01-05', // date
1, // append number
'cost', // type of data
array(
'reset' => true,
'data' => file_get_contents("reports/report_2013-12-23.csv"),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'));

at least incorrectly formed URL request...

Upload 4Mb file to YouTube took over 9 minutes since gzip compression added

The YouTube Service insert method was working fine prior to this update, but the since the gzip compression was added to IO/Stream.php, the time it takes is significantly increased.

I've used a debugger in my IDE and the time is spent in the call to file_get_contents() on line 111 in IO/Stream.php

$response_data = file_get_contents(
    $url,
    false,
    $context
);

I am running PHP 5.5.1, ZLib Version 1.2.7, Apache 2.4.6, Windows 7

I've a project going live for Adidas on monday that uses this code, so any assistance with it would be very appreciated.

Google Analytics - Simple example

I am trying to use this library to use Google Analysis API

I got this already:

<?php

require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_SECRET_API"); //security measures
$service = new Google_Service_Analytics($client);

/*
  https://www.googleapis.com/analytics/v3/data/
  ga?ids=ga%123456
  &dimensions=ga%3Acampaign
  &metrics=ga%3Atransactions
  &start-date=2013-12-25
  &end-date=2014-01-08
  &max-results=50
 */

$results = $service->data_ga;

echo '<pre>';
print_r($results);
echo '</pre>';

How to call that query in comments?

Support array/object query parameters

Would it be possible to support URL query parameters that are an array/object?

https://github.com/google/google-api-php-client/blob/86fb12d484da7fecbe04cecf767ac83008f24234/src/Google/Http/REST.php#L123

        if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
          foreach ($paramSpec['value'] as $value) {
            $queryVars[] = $paramName . '=' . rawurlencode($value);
          }
        } elseif ($paramSpec['type'] === 'object' && is_array($paramSpec['value'])) {
          $objParam = array($paramName => $paramSpec['value']);
          $queryVars[] = http_build_query($objParam);
        } else {
          $queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
        }

This would build a URL like:

example.com/api?query[param1]=foo

How can I retrieve contacts using this?

I have been looking through all of the examples

here https://developers.google.com/api-client-library/php/
and here https://github.com/google/google-api-php-client/tree/master/examples

and the services https://github.com/google/google-api-php-client/tree/master/src/Google/Service

but there doesn't appear to be any services which use the scopes which the api documentation states to use.

This may not be the right place to ask but I'm struggling to find any useful documentation or working tutorials which relate to this.

Cheers

status.embeddable not recognized on insert/update

Hi,

i'm not sure this an issue with the PHP api client, with the API itself or if i'm doing something wrong.

The value of status.embeddable is simply ignored for $youtube->videos->insert() and $youtube->videos->update() and is always set to the (default) value true.

I'm basically using the code from the PHP examples.

Inspecting the Google_Http_Request object (at this point) shows that the property is set correctly:

Google_Http_Request Object
(
    ...
    [postBody:protected] => {"snippet":{"categoryId":22,"description":"Test","tags":[""],"title":"Test"},"status":{"embeddable":false,"privacyStatus":"unlisted"}}
    ...
)

The responseBodyproperty shows that everything was accepted except embeddable:

Google_Http_Request Object
(
    ...
[responseBody:protected] => {
...
 "status": {
  "uploadStatus": "processed",
  "privacyStatus": "unlisted",
  "license": "youtube",
  "embeddable": true,
  "publicStatsViewable": true
 }
}
)

Any help or hints appreciated.

Reseller service working with sandbox ?

Hello,

I have a script using the Reseller Service to retrieve my subscriptions. It works fine with the production api, but when I use the sandbox I get this exception :

Error calling GET https://www.googleapis.com/apps/reseller/v1sandbox/subscriptions: (500) {
 "error": {
  "code": 500,
  "message": null
 }
}

To use the sandbox I modified the Google_Service_Reseller class like this :

changed

$this->servicePath = 'apps/reseller/v1/';

to

$this->servicePath = 'apps/reseller/v1sandbox/';

This is the code I use to retrieve my subscriptions :

set_include_path(get_include_path() . PATH_SEPARATOR . 'lib/google-api-client/src');

$keyLocation = 'keys/google-apps/xxxxxxxxxxx.p12';
$key = file_get_contents($keyLocation);

$client = new Google_Client();
$client->setApplicationName('myapp');
$service = new Google_Service_Reseller($client);

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

$cred = new Google_Auth_AssertionCredentials(
    'myOauth2EmailAddress',
    array(
        'https://www.googleapis.com/auth/apps.order',
        'https://www.googleapis.com/auth/apps.order.readonly'
        ),
    $key
);

$cred->sub = 'mysub';
$client->setAssertionCredentials($cred);

if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

$_SESSION['service_token'] = $client->getAccessToken();

$service->subscriptions->listSubscriptions();

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.