how to get analytics data without login into account - google-analytics

i am currently using gapi-google-analytics to get data from analytics without login credentials
but i am getting nothing in the output of this.getting blank page as a output
my code is given below:
require 'gapi-google-analytics/gapi.class.php';
$ga = new gapi('xxxxxxxxxxxxxx-uq0529xxxxxxxucf1pjlnk45t8nd00gup#developer.gserviceaccount.com','testproject.p12');
$metrics=array('pageviews');
$dimensions=array('browser','browserVersion');
$ga->requestReportData('11111554',$dimensions,$metrics,'-visits');
//echo"123";exit;
foreach($ga->getResults() as $result)
{
echo '<strong>'.$result.'</strong><br />';
echo 'Pageviews: ' . $result->getPageviews() . ' ';
echo 'Visits: ' . $result->getVisits() . '<br />';
}
echo '<p>Total pageviews: ' . $ga->getPageviews() . ' total visits: ' . $ga->getVisits() . '</p>';

Looks like you are trying to use a service account make sure that you go to the Admin page on Google Analytics website and add the service account email address as a user at the Account level. This will give the service account permission to access your data.
Update
Google Analytics data is private data, data that is owned by a user. In order to access someone's private data you must have there permission. You can not access Google Analytics data without some form of authentication.

Related

WordPress notifications not received in G-mail with altered header information

I have customized the default welcome e-mail send out by WordPress when you add a user, but when I change the default "From" information it no longer gets delivered to #gmail.com e-mailaddresses. I have tried it with multiple accounts, but always the same results. I haven't had any problems with #hotmail.com or any custom domain e-mailaddresses.
Below is the function I used to alter the default e-mail:
// Change the default welcome e-mail
add_filter( 'wp_new_user_notification_email', 'welcome__email', 10, 3 );
function welcome__email( $wp_new_user_notification_email, $user, $blogname ) {
$wp_new_user_notification_email['subject'] = sprintf(__( 'Company Name | Complete registration' ), $blogname, $user->user_login );
// Set password link
$key = get_password_reset_key( $user );
// Build the email
$message = sprintf(__('Welcome!')) . "\r\n\r\n";
$message .= 'By clicking the link below you can activate your account:' . "\r\n";
$message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . "\r\n\r\n";
$message .= "After setting a password you can login." . "\r\n";
$wp_new_user_notification_email['message'] = $message;
// Change header information
$wp_new_user_notification_email['headers'] = 'From: Company Name <noreply#example.com>';
return $wp_new_user_notification_email;
}
If I comment out the last part about the 'headers' the e-mail with link to set a password does get delivered to #gmail.com e-mailaddresses, but ofcourse the default name and e-mailaddress are show then.
I can't see what I am missing out here to make sure the e-mails get delivered to #gmail.com addresses, so I'm hoping anybody here is able to help me in the right direction.
PS: I do not have any SMPT plug-in set-up.
I just noticed the e-mails are not send to #gmail.com addresses because the sender e-mailaddress does not belong to the same domain as where the website is on. Once these match, there no longer is an issue.

Which PHP Script File is needed for ical() class in Google Calendar PHP API v3

I am getting an error in a PHP script I am building:
Fatal error: Class 'ical' not found in /home/abc/public_html/app/mods/googleCalendar_3.0/cache_events.php on line 74
Here is a snippet from my script file:
define('CLIENT_ID', 'ASDLJJLDSJLASDJLajdl;jdsljkASD;LKJASDLKJASD.apps.googleusercontent.com');
require_once('autoload.php'); // 2014-11-24 part of /usr/local/lib/php/google-api-php-client
require_once('/usr/local/lib/php/google-api-php-client/src/Google/Client.php'); // 2014-11-25
require_once('/usr/local/lib/php/google-api-php-client/src/Google/Service/Calendar.php'); // 2014-11-25
$ical = new ical('https://www.google.com/calendar/ical/CLIENT-ID/public/basic.ics');
$eventListArray = array_filter($ical -> events(), "locationfilter");
$eventCount = count($eventListArray);
print_r($eventListArray); echo "<br>";
echo "Event Count:" . $eventCount;echo "<br>";
exit;
I am simply trying to retrieve all events in my public calendar
Notes:
Calendar is publicly viewable
Just to make sure, I added my Auth & API's > Credentials > Service Account > Email Address to it just to be safe
If you want to use a service account your code is off quite a bit. I cant test this code my local webserver is acting up but it should be close you may have to tweek the $service->Events->list(); part it was kind of a guess. Make sure that you have the Service account email address added as a user on the calendar in question and it should work.
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Calendar($client);
// you should only need to do this once print this and you will
// find the calendarId for the one you are looking for.
$calendars = $service->calendarList->list();
$events = $service->events->list($yourCalendarID);
Note: all you need is the Google Dir you can remove everything above that you dont really need it. Code was edited from the only tutorial i have that shows this in PHP.

Google Analytics API Automated Login

I have this panel that i'm developing at my company where i will show the user's information from Google Analytics but i don't want the user to authorize or log in with his account every time he comes to the panel.
What i would like to do is: on the first time using my panel he would connect his Google account and i would save some info and on the next time he connects at my panel i would use this saved info to log on his account so i can list the Analytics info without ask for his permission or list that info even if he's not connected on is Google account right now.
Basically i would log in his account automatically and permit the 'app' to show the information.
I already have some code that connects on the API if he is connected on is Google account, but when he's not i get the login screen where he has to provide his email e password.
What i have so far is this:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Analytics PHP Starter Application");
$client->setClientId('KEY');
$client->setClientSecret('SECRET');
$client->setRedirectUri('RETURN URI');
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setAccessType('offline');
$service = new Google_Service_Analytics($client);
if(isset($_GET['logout']))
{
unset($_SESSION['token']);
}
if(isset($_GET['code']))
{
$client->authenticate($_GET['code']);
$_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($client->getAccessToken())
{
$props = $service->management_webproperties->listManagementWebproperties("12008145");//~all
print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";
$accounts = $service->management_accounts->listManagementAccounts();
//print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
$segments = $service->management_segments->listManagementSegments();
//print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";
$goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
//print "<h1>Goals</h1><pre>" . print_r($goals, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
header("Location: " . $authUrl);
}
?>
Is there any way to do that ? I have looked for it around everywhere and couldn't find something near it.
In google Api's, when user authenticate the first time, you receive a CODE (which you are already getting i suppose). Use this code to get refresh token (lifetime is (always), until and unless, user revokes the permissions). Save this refresh token in Database for further use. Refresh token is used to get access token(lifetime is a short time, returned in the expires in argument). Access token is to give you access to your user's data for some time. You can keep using refresh token to get access token whenever you need to access your user's data.
Whenever you want to access user's data, use refresh token to get access token and then use that access token to get user's data.
In your case, you are using google api php client, you can use Methods in Client.php like:
getAccessToken()---to get refresh token the first time. When you call this method, you get back a json in a form: let this json name be $accessToken
$accessToken = {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
"expires_in":3600,"id_token":"TOKEN", "created":1320790426}
parse json to take refresh_token($refreshToken = $accessToken.refresh_token) and save it for later use.
setAccessToken($accessToken)---call this to set the OAuth access token.
refreshToken($refreshToken)---Fetches a fresh OAuth access token with the given refresh token.
For further clearity, look at Client.php and also read:
https://developers.google.com/accounts/docs/OAuth2WebServer

Instagram public RSS feed

I was wondering how ink361 was creating an Instagram RSS feed from a username.
Example feed: http://ink361.com/feed/user/snoopdogg
Blog post:
http://blog.ink361.com/post/23664609916/new-rss-instagram-feed-feature-on-ink361-com
Any insight would be appreciated.
Thanks.
Instagram has a publicly accessible RSS API, it's hard to find any information about it, but it works for tags (we do use it).
For tags the syntax is the following:
http://instagr.am/tags/some-tag-you-want-to-follow/feed/recent.rss
I'm not sure whether they have something similar for users' feeds, as I've said it's really hard to find information about it and it may disappear from a day to another in favor of the official API, but right now it works for tags.
Here's an official blog post about it (although it covers only tags): http://blog.instagram.com/post/8755963247/introducing-hashtags-on-instagram
#user2543857 's answer was good. Unfortunately, the structure of the Instagram data has changed. As of the date of posting this, this will work. Copy/paste into a file on your PHP server and use like: yoursite.com/instarss.php?user=name_of_instagram_user This will return valid XML/RSS feed.
EDIT!! Naturally, the output of the page/JSON has changed with instagram's new look/feel. Here is updated code (June, 2015):
<?php
if (!isset($_GET['user'])) {
exit('Not a valid RSS feed. You didn\'nt provide an Instagram user. Send one via a GET variable. Example .../instarss.php?user=snoopdogg');
}
header('Content-Type: text/xml; charset=utf-8');
$html = file_get_contents('http://instagram.com/'.$_GET['user'].'/');
$html = strstr($html, '{"static_root');
$html = strstr($html, '</script>', true);
//$html = substr($html,0,-6);
$html = substr($html, 0, -1);
$data = json_decode($html);
// print_r($data->entry_data->ProfilePage[0]->user->media->nodes);
$rss_feed = '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel>';
$rss_feed .= '<title>'.$_GET['user'].'\'s Instagram Feed</title><atom:link href="http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"].'" rel="self" type="application/rss+xml" /><link>http://instagram.com/'.$_GET['user'].'</link><description>'.$_GET['user'].'\'s Instagram Feed</description>';
foreach($data->entry_data->ProfilePage[0]->user->media->nodes as $node) {
$rss_feed .= '<item><title>';
if(isset($node->caption) && $node->caption != '') {
$rss_feed .= htmlspecialchars($node->caption, ENT_QUOTES, ENT_HTML5);
} else {
$rss_feed .= 'photo';
}
// pubdate format could also be: "D, d M Y H:i:s T"
$rss_feed .= '</title><link>https://instagram.com/p/'.$node->code.'/</link><pubDate>'.date("r", $node->date).'</pubDate><dc:creator><![CDATA['.$_GET['user'].']]></dc:creator><description><![CDATA[<img src="'.$node->display_src.'" />]]></description><guid>https://instagram.com/p/'.$node->code.'/</guid></item>';
} // foreach "node" (photo)
$rss_feed .= '</channel></rss>';
echo $rss_feed;
?>
Actually, don't use the above code. I'll try to maintain this Gist in the future.
EDIT December 2016: I'm tired of chasing the every-changing Instagram output only to screen scrape it and have it change a few months later. I'd say just use the API.. If you are still interested in making an RSS feed from a user's page, this Gist should give you an idea of how to do it.
You can access the feed for any Instagram user using the /users/user-id/media/recent API endpoint. This endpoint requires an access_token which you can obtain by authorizing some user with Instagram (not necessarily the one you request the feed for). The process for receiving access_token is described here.
So what ink361 may be doing is get an access_token for themselves (their user on Instagram) and use that to make /users/user-id/media/recent requests for any other users' feeds. Simple as that.
Thanks to torvin for the tip.
Here is how you can get instagram images on your site without using the API.
Create json file from url and username (set this as a cron job, X times per day)
<?
$html = file_get_contents('http://instagram.com/username/');
$html = strstr($html, '["lib');
$html = strstr($html, '</script>', true);
$html = substr($html,0,-6);
file_put_contents("username.json",$html);
?>
Display a few images from json feed
<?
$json = file_get_contents('username.json');
$data = json_decode($json);
$img1 = $data[2][0]->props->userMedia[0]->images->standard_resolution->url;
$img2 = $data[2][0]->props->userMedia[1]->images->standard_resolution->url;
$img3 = $data[2][0]->props->userMedia[2]->images->standard_resolution->url;
print '<img src="'.$img1.'" />';
print '<img src="'.$img2.'" />';
print '<img src="'.$img3.'" />';
?>
If I were ink361, I would just crawl Instagram pages, parse HTML and turn it into RSS. No API, no authorization, no problems.
Unfortunately user2543857's solution above doesn't work anymore. Here's a version that works with the current profile page source though.
Create JSON file from URL and username (set this as a cron job, X times per day)
<?php
$json = file_get_contents('http://instagram.com/username');
$json = strstr($json, '{"entry_data"');
$json = strstr($json, '</script>', true);
$json = rtrim($json,';');
file_put_contents("username.json",$json);
?>
Display a few images from JSON feed
<?php
$json = file_get_contents('username.json');
$data = json_decode($json,true);
$img1 = $data['entry_data']['UserProfile'][0]['userMedia'][0]['images']['thumbnail']['url'];
$img2 = $data['entry_data']['UserProfile'][0]['userMedia'][1]['images']['thumbnail']['url'];
$img3 = $data['entry_data']['UserProfile'][0]['userMedia'][2]['images']['thumbnail']['url'];
print '<img src="'.$img1.'" />';
print '<img src="'.$img2.'" />';
print '<img src="'.$img3.'" />';
?>
You can get access to your rss feed for instagram by using their API. Their API uses oAuth2 for authentication. I use this method on my personal blog to pull in instagram pics on the homepage. I suspect this is how the ink361 site works. Ink361 will connect to the instagram api and prompt the user with a login via instagram box which they use to allow ink361 access to their instagram account. The ink361 site will cache the token received by instagram once authentication is successfull so they then can repeatedly go back to the instagram api on a periodic basis using the same token for authentication. Bingo you have access to the users data and you can create an rss feed from it.
The answer is simple.
To access user data you just must have valid access token.
The ink361 has an app in social network http://vk.com/app3225087 which stores authenticated users access tokens in db.
Its only left to find in db a valid one and get whatever user data you want

application loaded in iframe on facebook

I have an app loaded in iframe on facebook.
But after allow and redirected to my facekooksite from facebook authorization i cant fetch the "code" from the querrystring from within my code (because loaded in an iframe on facebook)
How will i be able to fetch the "code" parameter?
I guess you are following the server-side authentication flow. But since you are using Apps on Facebook, this flow will change since Facebook is sending a signed_request to your canvas iframe:
<?php
$app_id = "YOUR_APP_ID";
$canvas_page = "YOUR_CANVAS_PAGE_URL";
$auth_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page);
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"]);
}
?>
Obviously when you are on Facebook, the user is either connected to your app or not so if he/she is not connected then you redirect them to the authentication URL.

Resources