facebook share count - problem with FQL with different URLs - facebook

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 !

Related

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 API - Fatal error: Uncaught Exception: 601: Parser error: unexpected ')' at position 37

I have a FB app script and im trying to make it work but I get this error:
Fatal error: Uncaught Exception: 601: Parser error: unexpected ')' at position 37. thrown
in /home/altin/public_html/apps/empower/empowermix/base_facebook.php on line 658
Here is the part of the script where I get the error:
$friendsLists = $facebook->api('/me/friends');
foreach ($friendsLists as $friends)
{
$ile=count($friends);
}
$zapytanie=" (uid=".$friends[0]['id'].") ";
for($i=1;$i<$ile;$i++)
{
$zapytanie.=" or (uid=".$friends[$i]['id'].") ";
}
**$znajomi = $facebook->api(array("method"=> "fql.query", "query"=> "SELECT uid FROM page_fan WHERE ".$zapytanie." AND page_id='".$page_id."'")); //friends w fanpage**
$sql=mysql_query("SELECT * FROM '".$przedrostek_tab."ludzie' WHERE 'uid'=".$user_info['id']);
$czy_jest=mysql_fetch_array($sql);
foreach($znajomi as $k => $w)
{$znajomi_weryfikacja[$k]=$w['uid'];}
if($znajomi_weryfikacja)
{$znajomi_weryfikacja=( array_diff($znajomi_weryfikacja, explode("|",$czy_jest['znajomi_start'])));
if($czy_jest[0])
{foreach($znajomi_weryfikacja as $k => $w)
{$zaproszeni_znajomi.=$w.'|';}
mysql_query("UPDATE '".$przedrostek_tab."ludzie' SET 'zaproszeni_znajomi' = '$zaproszeni_znajomi' WHERE 'uid' =".$user_info['id']);}
}
Can anyone help suggest a solution? Maybe some of you may have faced similar problems before.
Thanks.
You have severe issues with your code handling Graph API response and construction of FQL query:
$facebook->api('/me/friends') returns associative array consisting of data (which contain friends details) and paging. (and just to be clear on naming this isn't friendlists but list of user's friends).
Error you get from API related to the fact that your query contain (uid=) in WHERE clause.
You can simply fix your loops:
$friendsList = $facebook->api('/me/friends');
$friends = $friendsList['data'];
$ile=count($friends);
$zapytanie=" (uid=".$friends[0]['id'].") ";
for($i=1;$i<$ile;$i++){
$zapytanie.=" or (uid=".$friends[$i]['id'].") ";
}
// ...
Actually there is couple of things that you should learn about FQL and Graph API:
You better retrieve only needed data and use IN instead of multiple OR
$response = $facebook->api('/me/friends?fields=id');
$friends = $response['data'];
$uids = array();
foreach ($friends as $friend)
$uids[] = $friend['id'];
$zapytanie = 'uid IN ('. implode(',', $uids) .')';
// ...
Also you may do this all in single FQL query
$fql = <<FQL
SELECT uid FROM page_fan WHERE page_id = {$page_id} AND uid IN (
SELECT uid2 FROM friend WHERE uid1 = me()
)
FQL;

How can I get friendship details in Facebook Graph API?

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.

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.