get likers of Facebook page and get count of those who like more than 200 pages - facebook

I'm trying to get a "list" of random likers who follow a Facebook Page. I'm using this code to get some fans (not random fans, but this is something else).
<?php
function fetch_fb_fans($fanpage_name, $no_of_retries = 10, $pause = 500000){
$ret = array();
/* get page info from graph */
$fanpage_data = json_decode(file_get_contents('http://graph.facebook.com/' . $fanpage_name), true);
if(empty($fanpage_data['id'])){
/* invalid fanpage name */
return $ret;
}
$matches = array();
$url = 'http://www.facebook.com/plugins/fan.php?connections=100&id=' . $fanpage_data['id'];
$context = stream_context_create(array('http' => array('header' => 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0')));
for($a = 0; $a < $no_of_retries; $a++){
$like_html = file_get_contents($url, false, $context);
preg_match_all('{href="https?://www\.facebook\.com/([a-zA-Z0-9._-]+)" data-jsid="anchor" target="_blank"}', $like_html, $matches);
if(empty($matches[1])){
/* failed to fetch any fans - convert returning array, cause it might be not empty */
return array_keys($ret);
}else{
// merge profiles as array keys so they will stay unique
$ret = array_merge($ret, array_flip($matches[1]));
}
// don't get banned as flooder
usleep($pause);
}
return array_keys($ret);
}
/*
print_r(fetch_fb_fans('cocacola', 2, 400000));
prints 73 unique fan names as array
*/
$contador = 0;
foreach (fetch_fb_fans('cocacola', 2, 400000) as $fan) {
$pageContent = file_get_contents('http://graph.facebook.com/'.$fan.'');
$parsedJson = json_decode($pageContent);
echo $parsedJson->username ."<br/>";
}
?>
Code from: Facebook API: Get fans of / people who like a page
This code give me some usernames. Now, my question, after searching Google... Is, can I get the number of pages that follow every user?
I know that Graph API let me know my likes but when I try to see other user likes it throws me an OAuthException error. I supose that I'm not doing right.
So I will apreciate some explanation about how to do this. I searched Google but I don't understand how it works.
Thanks.

The Facebook documentation is unfortunately not very clear: https://developers.facebook.com/docs/graph-api/reference/v2.2/user
However, getting the likes from a user requires:
User access token for the user
"User likes permission" granted on the access token, which is a special permission that Facebook approves on your app
Without an access token for the user you cannot see what pages they like.
While not supported, you could perhaps use a page scraper to find this information if they have it public.
Based on your question, it's not clear whether users log in to your app or if you're just trying to get information from one of your own pages, or another page. If you don't have users logging into your app, I'm afraid there's no way at all to get this information apart from a page scraper.

Related

get facebook share counts wordpress

i still have a problem on http://www.whaelse.com/en/grau-gruen-schwarz/ with the share counter.
Twitter and Google+ works fine for me.
With this code i've tried to load the facebook shares.
function get_likes($url) {
$json_string = file_get_contents('https://graph.facebook.com/?id='.$url);
$json = json_decode($json_string, true);
return intval( $json[$url]['shares'] );
}
and then
function getSocialCount($url){
$urlCurrentPage = get_permalink($post->ID);
$strPageTitle = get_the_title($post->ID);
echo '<li>facebook<span class="facebooksticky">'.get_likes($url).'</span></li>';
}
echo getSocialCount( get_permalink($post->ID));
but i still get 0 shares counter.
Could be a caching problem, just try it again tomorrow. Or try this endpoint, used by sharedcount.com:
https://api.facebook.com/method/links.getStats?urls=%%URL%%&format=json

Fetching FB user-id returns incorrect value ("1")

I have a very strange problem:
Sometimes (but not every time!) when I try to get the current user facebook ID, I get "1";
for example:
$config = array();
$config["appId"] = API_KEY;
$config["secret"] = SECRET;
$facebook= new Facebook($config);
$user=$facbook->getUser();
echo $user['id'];//returns 1;
Obviously - this it not the real user ID.
When I check if the access token is still good -I see that it is still valid. Also, even if I force the user to login again using:
FB.login(function(response) {
if (response.authResponse) {
top.location.href="<?php echo HOME_URL;?>"
}, {scope: 'publish_stream'});
Still getting the same result.
Any idea what could be the problem?
You should ONLY get an ID back from FB:
$user_id = $facbook->getUser();
echo $user_id;
You would later have to query the API for a user profile (which is what it looks like you are doing):
$user_profile = $facebook->api('/me');
Reference:
http://developers.facebook.com/docs/reference/php/facebook-api/

Facebook API how to get User Pages

I am using the following code to grab info for the Facebook user.
Is there a way to get the user Pages (if the user has one or more Facebook Pages) and the IDs of these pages?
$user = $_POST['uid']; //the returned user ID from Facebook
$key = $_POST['usid']; //the returned session ID from Facebook
$accesstoken = $_POST['accesstoken']; //the returned accesstoken from Facebook
$image = "http://graph.facebook.com/" .$user ."/picture?type=large"; //Facebook Profile Picture
$name = json_decode(file_get_contents('https://graph.facebook.com/' . $user))->name; //Name of the user account on Facebook
$link = json_decode(file_get_contents('https://graph.facebook.com/' . $user))->link; //Link of the user profile on Facebook
$gender = json_decode(file_get_contents('https://graph.facebook.com/' . $user))->gender; //Gender of the user on Facebook
$locale = json_decode(file_get_contents('https://graph.facebook.com/' . $user))->locale; //Location of the user on Facebook
$url = "https://graph.facebook.com/". $user ."/feed?limit=1&access_token=".$accesstoken; //We get the latest status update on the Facebook Wall
$json = file_get_contents($url);
$jsonData = json_decode($json);
foreach($jsonData->data as $val) {
if($val->from->id == $user) {
$statusmessage = $val->message; //Finally we got the latest status update if there is one on The Facebook Wall
break;
}
}
If you asking how to get additional user profiles, of a single user, based on their Facebook Id: the answer is you can't. Facebook mandates one profile per user. And while in real life a user can have multiple profiles, there is no reliable means of extracting that data from the graph.
However, if you're asking how to get the ids of pages the user admins then use:
https://graph.facebook.com/USER_ID/accounts
this will require a valid access token for the given user.

Getting user info after login for facebook application

I have written a small piece to get the user to login :
<?php
include_once ('facebook.php');
$api_key = 'xxxxxxxxxxxxx';
$secret = 'xxxxxxxxxxxxx';
global $facebook;
$facebook = new Facebook($api_key, $secret);
$facebook->require_frame();
#Ask user to login if not logged in
$is_tab = isset($_POST['fb_sig_in_profile_tab']);
if( !$is_tab ){
$uid = $facebook->require_login($required_permissions = 'email,status_update,offline_access');
}
else{
$uid = $facebook->get_profile_user();
}
I need to retrieve the users info once I have the uid. Unfortunately I cannot find the api calls for it and there is a no IDE for facebook :(. Can anyone point me to the api's or give me here. I want to get users username, city, zipcode.
I coudnt get this to work : facebook.Schema.user user = api.users.getInfo();
I think it is for the new API lib.
Thanks.
P.S: I am not using graph APIs, because I found them to be poorly documented and I got stuck with them for a while so decided to abandon them atleast for now.
You can get it like this:
$user_info = $facebook->api_client->users_getInfo($uid, "name, city, zipcode");
print_r($user_info);
More Info:
http://developers.facebook.com/docs/reference/rest/users.getInfo

How can I get Facebook Profile image from email?

There's an outlook plugin called Xobni that has a really cool feature, if a contact has an email address, it will fetch that contact's profile picture and display it. Their FAQ states the following:
Xobni sends an encrypted email address to Facebook to retrieve the Facebook profile for the person who is currently being viewed in the Xobni sidebar. Your own Facebook profile is never altered by Xobni, and all Facebook privacy settings are strictly followed when viewing other profiles.
I'd like to duplicate this functionality. However, I can't figure out which API call they're using. I'm assuming when they say "encrypted email address" that's laymen's terms for the email hash. Once a username is derived, the graph api looks ideal for actually fetching the image, but I'm having trouble going from email hash to profile ID.
You can query the following URL to get user id (if one exists on Facebook):
https://graph.facebook.com/search?access_token=YOUR_ACCESS_TOKEN&q=EMAIL_ADDRESS_URL_ENCODED&type=user
Then <img src="https://graph.facebook.com/USER_ID/picture"> gives you the picture.
More info: article at codinglogs.com
I am searching for a way to do this exact thing... No attempts have worked yet.
Has anyone been able to find a solution?
Update: I've put together this snippet in PHP. It's just about the only way I've been able to accomplish my goal. I'm not sure how Xobni is doing it (I'm sure they are less intrusive about it)
<?php
/* Email to Search By */
$eml = 'user#domain.com';
/* This is where we are going to search.. */
$url = 'http://www.facebook.com/search.php?q=' . urlencode($eml);
/* Fetch using cURL */
$ch = curl_init();
/* Set cURL Options */
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* Tell Facebook that we are using a valid browser */
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13');
/* Execute cURL, get Response */
$response = curl_exec($ch);
/* Check HTTP Code */
$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
/* Close cURL */
curl_close($ch);
/* 200 Response! */
if ($response_code == 200) {
/* Parse HTML Response */
$dom = new DOMDocument();
#$dom->loadHTML($response);
/* What we are looking for */
$match = 'http://www.facebook.com/profile.php?id=';
/* Facebook UIDs */
$uids = array();
/* Find all Anchors */
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$href = $anchor->getAttribute('href');
if (stristr($href, $match) !== false) {
$uids[] = str_replace($match, '', $href);
}
}
/* Found Facebook Users */
if (!empty($uids)) {
/* Return Unique UIDs */
$uids = array_unique($uids);
/* Show Results */
foreach ($uids as $uid) {
/* Profile Picture */
echo '<img src="http://graph.facebook.com/' . $uid. '/picture" alt="' . $uid . '" />';
}
}
}
?
It is no longer possible to search user info with email address via Facebook Graph API. While it still works if you have the Facebook user ID, but if you can't get the Facebook ID with the search API, you can no longer do this.
https://developers.facebook.com/x/bugs/453298034751100/
The API will return the following response:
{
"error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}
Many thanks #McHerbie, you gave me the clue to FINALLY get my code working. The key is the urlencode() function to encode email!!! thanks, this is my working code using PHP Simple HTML Dom Parser:
public function getFacebookPictureByScrapping($email="your#email.com", $file="fbPicture.jpg") {
require_once('protected/extensions/simplehtmldom/simple_html_dom.php');
$userEmail = urlencode($email);
ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13');
$url = "http://www.facebook.com/search.php?q=$userEmail&type=all&init=srp";
$html = new simple_html_dom();
$html = file_get_html($url);
if (is_object($picture = $html->find(".uiList .img",0))) {
$image = file_get_contents($picture->src, false);
file_put_contents($file);
return $file;
} else {
return null;
}
}
I know this post is a bit old, but only just now found it - you might try the FullContact Person API (full disclosure - I'm biased, I work for them):
http://www.fullcontact.com/developer/
On the one hand, it will pull the associated social media profiles when you query based on email so that you can find and pull the associated profile...but on the other hand, you can also save some time & use it to pull the profile images directly.
The response schema includes:
"photos":
[
{
"typeId": [photo type],
"typeName": [photo type name],
"url": [photo url],
"isPrimary": [boolean]
}
]
More info: http://www.fullcontact.com/developer/docs/person/#lookup-by-email-3