How can I get friendship details in Facebook Graph API? - facebook

How can I get a friendship detail for two people? So for example in the web it will be:
http://www.facebook.com/<my_id>?and=<friend_id>
Is there any way I can do this in Graph API? Furthermore can I get specific items such as photos together, wall posts between us, etc? (Not documented AFAIK, but many Graph API features aren't anyway...)
EDIT: I think it should be possible with Graph API. For example getting family details (brother, sister, parents, etc) is not documented yet I still able to do it.

You can simulate a friendship query by doing multiple FQL queries. For example, to get all the photos between two friends A and B, you can:
Get all photos (p) from A
Get all tags of B in p (query on the photo_tags table)
Get all comments made by B on p (query on the comments table)
Repeat, this time selecting photos from B.
You can apply the same concept on other things such as posts, likes, videos etc.

Yes, I think you can also do the same thing phillee answered with the Graph API instead of FQL:
Get user's photos https://graph.facebook.com/USERID/photos
Get each photo's tags https://graph.facebook.com/PHOTOID/tags
Sort through the list of photo tags, and grab all photos with the Friend in them
Get each photo's comments https://graph.facebook.com/PHOTOID/comments
Sort through the list of photo comments, and grab all comments left by the friend
As the other answer also said: rinse and repeat for all data you want
https://graph.facebook.com/USERID/feed
https://graph.facebook.com/USERID/posts
etc etc, see all connections here: http://developers.facebook.com/docs/reference/api/user/
For the interests, movies, activities, etc just make an API call for both (https://graph.facebook.com/ONEUSER/music and https://graph.facebook.com/OTHERUSER/music) and find the intersection of the two sets of data (loop through each list and save all matches to a separate list of mutual Likes)
There are no specific API calls for friendships though, so you will have to build your own. My guess is that Facebook is doing exactly this on their Friendship pages :)
It should be just as easy with FQL as with the REST API... maybe even easier with FQL since you can add WHERE conditions and get back just the data you need (SELECT * FROM comments WHERE fromid = FRIENDID), instead of sorting through the big list returned by the API (unless there is a way to add conditions to API request URLs?).

If I understand properly you want to "View Friendship"
This type of query is not directly possible using the Graph API (at the moment). You would need to gather the information from each resource endpoint and then do some relating on your own part to "View Friendship"

This is what I have been using:
<?php
function main()
{
global $Fb;
$Fb = new Facebook(array('appId'=>FB_API_ID,'secret'=>FB_API_SECRET));
$logoutUrl = $Fb->getLogoutUrl();
$loginUrl = $Fb->getLoginUrl();
$user = fb_loguser($Fb);
if ($user)
{
$txt .= "<p align=\"center\">Logout</p>";
$txt .= "<h3 align=\"center\">You</h3>";
$access_token = $Fb->getAccessToken();
$user_profile = $Fb->api('/me');
$txt .= "<p align=\"center\">
<img src=\"https://graph.facebook.com/".$user."/picture\"></p>";
$txt .= fb_friends_list($user_profile,$access_token);
}
}
function fb_loguser($facebook)
{
global $Fb;
$Fb = $facebook;
$user = $Fb->getUser();
if ($user)
{
try
$user_profile = $Fb->api('/me');
catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
return($user);
}
function fb_friends_list($access_token)
{
global $Sess,$Fb;
$friends = $Fb->api('/me/friends'); // return an array [data][0 to n][name]/[id]
$siz = sizeof($friends['data']);
$txt = "<h3>Your FRIENDS on FACEBOOK</h3>";
$txt .= "<table>";
for ($i=0; $i<$siz; $i++)
{
$fid = $friends['data'][$i]['id'];
$src = "http://graph.facebook.com/".$fid."/picture";
$txt .= "<tr><td><img src=\"".$src."\" /></td>";
$txt .= "<td>".$friends['data'][$i]['name'] . "</td>";
$txt .= "<td>" . $fid . "</td></tr>";
}
$txt .= "</table>";
return($txt);
}
?>
Call main()!

Getting the photos where two (or more) users are tagged in:
SELECT pid, src_big FROM photo
WHERE pid IN(
SELECT pid FROM photo_tag WHERE subject=me())
AND pid IN(
SELECT pid FROM photo_tag WHERE subject=FRIEND_ID)
AND pid IN(
SELECT pid FROM photo_tag WHERE subject=ANOTHER_FRIEND_ID)
...

http://bighnarajsahu.blogspot.in/2013/03/facebook-graph-api-to-get-user-details.html
This is the complete code to get the friendlist in Fb.

Related

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

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.

Facebook developer roadmap: Deprecating 'comments' field & Removing 'count' from 'comments'

I have noticed the [new changes in FB Developer]: https://developers.facebook.com/roadmap/
I'd like to know what you think I need to change in my code.
I have wordpress and I have a function that counts the total number of comments, and of course it still need to works also after July 10.
function full_comment_count() {
global $post;
$url = get_permalink($post->ID);
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
$json = json_decode($filecontent);
$count = $json->$url->comments;
$wpCount = get_comments_number();
$realCount = $count + $wpCount;
if ($realCount == 0 || !isset($realCount)) {
$realCount = 0;
}
return $realCount;
}
Is it as simple as changing:
$count
to
$total_count
or something else needs to be changed as well in the code?
Thank you
Facebook Roadmap:
We are removing the undocumented 'count' field on the 'comments'
connection in the Graph API. Please request
'{id}/comments?summary=true' explicitly if you would like the summary
field which contains the count (now called 'total_count')
...file_get_contents is VERY bad, CURL would be better, but more complicated. the best way to use the graph api in this case is the php sdk: https://github.com/facebook/facebook-php-sdk
anyway, i guess those changes are needed:
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
...this is still correct, with a var_dump right after this line (or after the json decode) you see that there is an "id". with that id, you have to make a second call to the graph api:
$comments= file_get_contents('https://graph.facebook.com/' . $id . '/comments?summary=true);
the rest is easy-peasy basic php stuff, just do a var_dump of $comments after using json_decode again.

Using facebook javascript sdk to process fql query

I have just put implemented Facebook connect on my web-site using the JavaScript SDK. Now I would like to process an fql query.
So I have two questions:
Is it possible using only JavaScript fql as "SELECT id, name FROM user WHERE uid IN (SELECT uid1 FROM friends WHERE uid2=me())" ?
Because when I tried some PHP SDK code using the facebook doc
PHP:
$app_id = 'MY_ID';
$app_secret = 'MY_APP_SECRET';
$my_url = 'POST_AUTH_URL';
$code = $_REQUEST["code"];
$_REQUEST["code"] is quite normally not recognized and I don't know what is the "'POST_AUTH_URL'" because I didn't use the PHP SDK to process the Facebook-connect. Does anyone have an idea?
Using method: 'fql.query' is part of the deprecated REST API.
A better, future-proof way IMHO is to send your queries against the Graph API:
FB.api("/fql?q={your urlencoded query}", callback() { … } );
Using the JavaScript SDK you can easily execute an FQL query -
FB.api(
{
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid=me()'
},
function(response) {
alert('Your name is ' + response[0].name);
}
);
Don't forget to request all the permissions you need before executing any queries...
Reference - https://developers.facebook.com/docs/reference/javascript/
Sorry I can't comment yet but to clarify this helpful answer; what worked for me was formatting the FQL API call the same way I would a Graph API call with {fields: "ex1,ex2"}:
var fqlRequest = "SELECT name FROM user WHERE uid = me()";
FB.api("/fql",{q:fqlRequest}, function(response){
// do cool stuff with response here
});
Note that I did NOT have to URL encode the string and it worked fine for me (I had used
encodeURI(fqlRequest) before and it returned an unexpected % error).
Also remember to quote literals if you use them:
var id = "1234567890";
var fqlRequest = "SELECT name FROM user WHERE uid = ' " + id + " ' ";

facebook share count - problem with FQL with different URLs

I have a plugin on my page which allows users to share articles on my site on facebook, but each url is appended with their user id.
What I want to do is count the number of total share regardless of the shareers user id.
However I cannot get the FQL to work as the where parameter will not accept the LIKE function..
the pages will be something like:
page1.php?sid=2
page1.php?sid=34
page1.php?sid=12
But I want to retrieve the total shares for page1.php regardless of the sid.
The LIKE function doesnot work in FQL does anyone have any ideas as I am struggling
current code:
https://api.facebook.com/method/fql.que … ge1.php%27
You can use FQL to make your query :
$fql = 'SELECT total_count FROM link_stat WHERE url="http://google.com"';
$json = file_get_contents('https://api.facebook.com/method/fql.query?format=json&query=' . urlencode($fql));
$data = json_decode($json);
echo $data[0]->total_count;
Here, total_count gives you the number of shares for the link.
If you have several URL to query, you can make all of that in only one query by using OR :
SELECT url, total_count FROM link_stat WHERE url="..." OR url="..."
Here is an example is you want to get the number of shares for theses 3 URLs :
$urls = array(
"http://www.example.com/page1.php?sid=2",
"http://www.example.com/page1.php?sid=12",
"http://www.example.com/page1.php?sid=34",
);
function wrap($url) {
return 'url="' . $url . '"';
}
$fql = 'SELECT url, total_count FROM link_stat WHERE ';
$fql .= implode(" OR ", array_map("wrap", $urls));
$json = file_get_contents('https://api.facebook.com/method/fql.query?format=json&query=' . urlencode($fql));
$data = json_decode($json);
And $data is an array of 3 objects with the share number for each URL :
array(4) {
[0]=> object(stdClass)#2 (2) {
["url"]=> string(17) "http://www.example.com/page1.php?sid=2"
["total_count"]=> int(1318598)
}
[1] => ...
[2] => ...
[3] => ...
}
Then you just have to go through the array to make a sum.
Hope that helps !

Fetching friends' birthdays from facebook profile

I want to fetch 'birthdays' of users, and their friends on my website, from their facebook profiles (with their facebook credentials supplied).
Is their a feature in Facebook API/Connect that I can use to fetch these details from facebook as possible on Native Facebook Apps using Facebook API.
I want to store this data in my DB, and users will be asked for their facebook credentials and consent before this is done.
Read the api documentation things like this are easily done. You can do it like this:
$facebook = new Facebook( $apikey, $secret );
$uid = $facebook->require_login();
$friends = $facebook->api_client->friends_get(); // $friends is an array holding the user ids of your friends
foreach( $friends as $f ) {
$data = $facebook->api_client->fql_query( "SELECT birthday_date FROM user WHERE uid=$f" );
// $data[0] is an array with 'birthday_date' => "02/29/1904"
// see api documentation for other fields and do a print_r
}
So recently I wanted to check my friends to see if any of them had their birthday for the current day. Using FQL this is super easy and I encourage you to explore FQL more because it will yield a more efficient solution than, say, what Pierre kindly offered. Here is a small snippet of the code:
$friends = $facebook->api_client->friends_get();
$uids = "";
foreach($friends as $f) {
$uids .= "uid=$f OR ";
}
$query_uids = substr($uids,0,strlen($query_uids)-4);
date_default_timezone_set('UTC');
$current_date = date("m/d");
echo "<br />Searching for birthdays for the given month/day: $current_date<br />";
$data = $facebook->api_client->fql_query( "SELECT name, uid FROM user WHERE ( ($query_uids) AND strpos(birthday_date,'$current_date') >= 0 )" );
if(count($data) > 0) {
foreach($data as $d) {
print_r($d);
}
} else {
echo "<br />No Birthdays Today<br />";
}
require_once('facebook-platform/client/facebook.php');
$facebook = new Facebook(API_KEY, SECRET);
$facebook->require_login();
function getInfo($user_list, $fields)
{
try
{
$u = $facebook->api_client->users_getInfo($user_list, $fields);
return $u;
}
catch (FacebookRestClientException $e)
{
echo $e->getCode() . ' ' . $e->getMessage();
}
}
function getFriendsBirthdays($user_id)
{
$f = $_REQUEST['fb_sig_friends'];
$f = explode(',', $f);
$birthdays = array();
foreach($f as $friend_id)
{
$birthdays[] = getInfo($friend_id, 'birthday');
}
return $birthdays;
}
Do something like that or use the Batch API to do multiple calls at once. Check the Facebook API.
You could fetch it via the API, but Facebook's terms strictly forbid you from storing anything other than their user ID in your database - see the developer wiki for details. You will need to query the API each time.