Google Analytics API get Profile ID instead or with Domains - api

This is how I print Domains from any Google Analytics account. How do I print Profile IDs instead (or with the Domains)?
global $_params, $output_title, $output_body;
$output_title = 'Adwords';
$output_nav = '<li>Logout</li>'."\n";
$output_body = '<h1>Google Adwords Access demo</h1>
<p>The following domains are in your Google Adwords account</p><ul>';
$props = $service->management_webproperties->listManagementWebproperties("~all");
foreach($props['items'] as $item) {
$output_body .= sprintf('<li>%1$s</li>', $item['name']);
}
$output_body .= '</ul>';
This line is the function that gets the Domains:
$props = $service->management_webproperties->listManagementWebproperties("~all");
I need something to get Profile IDs for multiple Domains now.
Thanks in advance.

This example below should help you print all the profile ids for a particular account XXXX and property UA-XXXX-Y.
/**
* This example requests a list of views (profiles) for the authorized user.
*/
$profiles = $analytics->management_profiles->listManagementProfiles('XXXX', 'UA-XXXX-Y');
foreach ($profiles->getItems() as $profile) {
print("view (profile) id: $profile->getId()");
}
You can checkout the API documentation for view (profiles) for more detailed examples.
You may also find it useful to use the account summaries api. It provides an easy way to iterate through all levels of the Google Analytics Accounts -> Properties -> view (profiles)
$accounts = $analytics->management_accountSummaries
->listManagementAccountSummaries();
foreach ($accounts->getItems() as $account) {
$html = <<<HTML
<pre>
Account id = {$account->getId()}
Account kind = {$account->getKind()}
Account name = {$account->getName()}
HTML;
// Iterate through each Property.
foreach ($account->getWebProperties() as $property) {
$html .= <<<HTML
Property id = {$property->getId()}
Property kind = {$property->getKind()}
Property name = {$property->getName()}
Internal property id = {$property->getInternalWebPropertyId()}
Property level = {$property->getLevel()}
Property URL = {$property->getWebsiteUrl()}
HTML;
// Iterate through each view (profile).
foreach ($property->getProfiles() as $profile) {
$html .= <<<HTML
Profile id = {$profile->getId()}
Profile kind = {$profile->getKind()}
Profile name = {$profile->getName()}
Profile type = {$profile->getType()}
HTML;
}
}
$html .= '</pre>';
print $html;
}

Related

whmcs server-side pagination

I'm working with WHMCS and I notice that list views are not working well.
That's because in the clientarea's list views I have tousans thousands of records to display and the DataTables is crashing.
Is there a way to paginate from the server-side? I will appreciate any idea.
Here is an idea: let' say you are viewing the Domains list page, you can use ClientAreaPage hook to create a variable to load a "paged" copy of domains:
add_hook( 'ClientAreaPage', 1, function( $vars )
{
$myVars = array();
if (App::getCurrentFilename() == 'clientarea' && isset($_GET['action']) && $_GET['action'] == 'domains') {
$domains2 = array();
foreach($vars['domains'] as $k => $domain) {
if ($k < 3) {//your code to handle pagination
$domains2[] = $domain;
}
}
$myVars['domains2'] = $domains2;
$myVars['currentpage'] = 1;
}
return $myVars;
});
In clientareadomains.tpl (template file), you need to change $domains to $domains2:
{foreach key=num item=domain from=$domains2}
Of course, it is not simple task, you need to handle pagination in the hook and the tpl files.
Hope it helps.

Recieving very slow response from twitter usertimeline requests, is the twitter API slow?

I am retrieving tweets from multiple accounts (around 20) and displaying them on a page. The request are very slow and my page takes one to two minutes to load. I am using the twitteroauth library (PHP). If i reduce the number of accounts, the loading time kind of decreases.
Here's the function
//twitter credentials and connection
$consumer_key = variable_get('tw_consumer_key', 'xxxxxxxxxxx'); //consumer key
$consumer_secret = variable_get('tw_consumer_secret', 'xxxxxxx'); // consumer secret
$oauth_token = variable_get('tw_access_token', 'xxxxxxxxxxxx'); //oAuth Token
$oauth_token_secret = variable_get('tw_access_token_secret', 'xxxxxxxxxx'); //oAuth Token Secret
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
$connection->host = "https://api.twitter.com/1.1/";
//Retrieve feeds now
foreach ($twitter_accounts as $account_twitter) {
if (!empty($account_twitter['lien'])) {
$page_url = $account_twitter['lien'];
$twitter_name = $account_twitter['compte'];
$query = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $twitter_name . '&exclude_replies=true&include_rts=true&include_entities=true';
$content = $connection->get($query);
if (sizeof($content) > 0 && empty($content->errors)) {
$tw_tweets['posts'] = $content;
$tw_tweets['url'] = $page_url;
$twitter_feeds[] = $tw_tweets;
}//end if sizeof
else {
if (!empty($content->errors)) {
$error = '';
$error = (isset($content->errors[0]->message)) ? $content->errors[0]->message : '';
$error .= (isset($content->errors[0]->code)) ? ' code' . $content->errors[0]->code : '';
watchdog('ffbb_hubsocial', 'Twitter Account ' . $account_twitter['compte'] . ' failed to return results :' . $error);
}
}
}
}
Is the API slow ?
Anyone knows if the problem is with twitter ?
Duplicate question: Why are the Twitter api calls so slow?
As the above answer states, try testing the URL in your browser and see how long it takes. Hence, you'll be able to see if the issue is on your side or due to Twitter.

Update video with YOUTUBE google-api-php-client

I'm trying update the video metadata with Youtube API. The API which I'm using is google-api-php-client.
That API works perfectly in upload and delete processes, but when I want update the video info I don't know what parameters I have to use.
This is the code:
try
{
// Build the Needed Video Information
$snippet = new Google_VideoSnippet();
$snippet->setTitle($_POST['videoTitle']);
$snippet->setDescription($_POST['videoDescription']);
$snippet->setTags(array($_POST['videoTags']));
$snippet->setCategoryId(22);
// Set the Video Info and Status in the Main Tag
$video = new Google_Video();
$video->setSnippet($snippet);
// Send the video to the Google Youtube API
$created_file = $youtube->videos->update('snippet', $video, array(
WHAT PARAMETERS!!!???!!
));
// Get the information of the uploaded video
print_r($createdFile);
}
catch (Exception $ex)
{
echo $ex;
}
Someone knows this? ? i'd like keep using this API because all my aplication use it.
Thank you in advanced.
To update a video, first you need to use videos->list with id=video_id, then update the part intended, wrap all subparts till to the video itself into google objects, and send an update request. (We will work to make this simpler)
Here's an update tags sample which ultimately updates the video, you can use it.
/**
* This sample adds new tags to a YouTube video by:
*
* 1. Retrieving the video with "youtube.videos.list" method setting the "id" parameter
* 2. Appending new tags to Video Resource's snippet.tags[] list
* 3. Updating the video itself via youtube.videos.update API call, supplying a new video via a
* binary upload to replace the old one.
*
* #author Ibrahim Ulukaya
*/
// Call set_include_path() as needed to point to your client library.
require_once 'Google_Client.php';
require_once 'contrib/Google_YouTubeService.php';
session_start();
/* You can acquire an OAuth 2 ID/secret pair from the API Access tab on the Google APIs Console
<http://code.google.com/apis/console#access>
For more information about using OAuth2 to access Google APIs, please visit:
<https://developers.google.com/accounts/docs/OAuth2>
Please ensure that you have enabled the YouTube Data API for your project. */
$OAUTH2_CLIENT_ID = 'REPLACE ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE ME';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// YouTube object used to make all Data API requests.
$youtube = new Google_YoutubeService($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Check if access token successfully acquired
if ($client->getAccessToken()) {
try{
// REPLACE with the video ID that you want to update
$videoId = "VIDEO_ID";
// Create a video list request
$listResponse = $youtube->videos->listVideos("snippet",
array('id' => $videoId));
$videoList = $listResponse['items'];
if (empty($videoList)) {
$htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId);
} else {
// Since a unique video id is given, it will only return 1 video.
$video = $videoList[0];
$videoSnippet = $video['snippet'];
$tags = $videoSnippet['tags'];
// $tags is null if the video didn't have any tags, so we will check for this and
// create a new list if needed
if (is_null($tags)) {
$tags = array("tag1", "tag2");
} else {
array_push($tags, "tag1", "tag2");
}
// Construct the Google_Video with the updated tags, hence the snippet
$updateVideo = new Google_Video($video);
$updateSnippet = new Google_VideoSnippet($videoSnippet);
$updateSnippet->setTags($tags);
$updateVideo -> setSnippet($updateSnippet);
// Create a video update request
$updateResponse = $youtube->videos->update("snippet", $updateVideo);
$responseTags = $updateResponse['snippet']['tags'];
$htmlBody .= "<h3>Video Updated</h3><ul>";
$htmlBody .= sprintf('<li>Tags "%s" and "%s" added for video %s (%s) </li>',
array_pop($responseTags), array_pop($responseTags),
$videoId, $updateResponse['snippet']['title']);
$htmlBody .= '</ul>';
}
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Video Updated</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>

Ebay API with description

How do I get the Ebay API to return a description?
I have some code that makes an API call as follows:
http://svcs.ebay.com/services/search/FindingService/v1?
callname=findItemsAdvanced&
responseencoding=XML&
appid=appid&
siteid=0&
version=525&
QueryKeywords=keywords;
It returns items, but it's missing the full description text. I'm not seeing the next step to ask for the detailed descriptions.
You have to use Shopping API, for instance: http://developer.ebay.com/DevZone/shopping/docs/CallRef/GetSingleItem.html#sampledescriptionitemspecifics
I use following (very simple function to get Item detail from ebay):
function eBayGetSingle($ItemID){
$URL = 'http://open.api.ebay.com/shopping';
//change these two lines
$compatabilityLevel = 967;
$appID = 'YOUR_APP_ID_HERE';
//you can also play with these selectors
$includeSelector = "Details,Description,TextDescription,ShippingCosts,ItemSpecifics,Variations,Compatibility";
// Construct the GetSingleItem REST call
$apicall = "$URL?callname=GetSingleItem&version=$compatabilityLevel"
. "&appid=$appID&ItemID=$ItemID"
. "&responseencoding=XML"
. "&IncludeSelector=$includeSelector";
$xml = simplexml_load_file($apicall);
if ($xml) {
$json = json_encode($xml);
$array = json_decode($json,TRUE);
return $array;
}
return false;
}

How to use Twitter Api To Get more than 20 list Members in a single request?

i want to get more than 20 users using the the twitter api in a single request
is there any parameter that specifies it?
i am using this api
http://api.twitter.com/1/Barelyme/Politics/members.xml?cursor=-1
According to the Twitter List API Docs:
http://apiwiki.twitter.com/Twitter-REST-API-Method:-GET-list-members
You cant get more than 20 in a single request.
If you're using twitteroauth by abraham, you can iterate through the pages of list members (this example assumes $connection is already defined by a functional implementation of twitteroauth):
$user = $connection->get('account/verify_credentials'); //Gets/Tests credentials
$listmembers = $connection->get("{$user->screen_name}/LISTNAMEORID/members"); //Gets first page of list members; MUST edit "LISTNAMEORID"
$pagevalue = ""; //Set page value for later use
if($listmembers->next_cursor == 0){ //There is only one page of followers
for ($j=0, $k=count($listmembers->users); $j<$k; $j++){
//Your actions here
//print_r($listmembers); //Displays the page of list members
}
} else { //There are multiple pages of followers
while ($pagevalue!=$listmembers->next_cursor){
for ($j=0, $k=count($listmembers->users); $j<$k; $j++){
//Your actions here
//print_r($listmembers); //Displays the page of list members
}
$pagevalue = $listmembers->next_cursor; //Increment the 'Next Page' link
$listmembers = $connection->get("{$user->screen_name}/LISTNAMEORID/members", array('cursor' => $pagevalue)); //Gets next page of list members; MUST edit "LISTNAMEORID"
}
}
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$listmembers = $connection->get("MexicoTimes/mexicanpoliticians/members");
$members = array();
while ($listmembers->next_cursor_str != "0") {
foreach($listmembers->users as $user)
$members[] = $user;
$cursor = $listmembers->next_cursor_str;
$listmembers = $connection->get("MexicoTimes/mexicanpoliticians/members", array('cursor' => $cursor));
}
This one worked for me with Abraham's Twitteroauth
Probably not though, you can poll multiple times > 1 for more data.
Given that twitter said you can't do it, you Probably can't