Facebook API - comment count via FQL - facebook

I'm trying to display Facebook comment counts in <div id="comments">
It has to be via Facebook Query Language (FQL). This post is almost exactly what I need:
Facebook Graph Api url comments and shares count doesn't work anymore
But how do I display the comment_count (from the query) into a div? i.e. how do I process that data? So far, I have:
$(function(){
$.ajax({
url: 'https://graph.facebook.com/fql?q=SELECT%20comment_count%20FROM%20link_stat%20WHERE%20url=%27e',
dataType: 'jsonp',
success: function(data) {
if(data.comment_count)
{
$('body').find('#comments').html('Comments ('+jsonp.data.comment_count+')');
}else{
$('body').find('#comments').html('Comments (0)');
}
}
});
});

I did it like this to update my div with the likes count like this
$fql = "SELECT url, normalized_url, share_count, like_count, comment_count, ";
$fql .= "total_count, commentsbox_count, comments_fbid, click_count FROM ";
$fql .= "link_stat WHERE url = '".$url."'";
$j.ajax({
url: 'https://api.facebook.com/method/fql.query?format=json&query=<?php echo urlencode($fql);?>',
dataType: 'jsonp',
success: function(data)
{
$j(".comment_count").html(data.comment_count);
}
});
works for me like a charm.

For my part,
I used php code to get the comment count via fql. First, you need to download the facebook php sdk and load it at the top of your page:
require_once("src/facebook.php");
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_SECRET_KEY',
);
$facebook = new Facebook($config);
Then, the fql query:
$url = 'http://www.yoururl.com/;
$fquery = 'SELECT comment_count, share_count, like_count FROM link_stat WHERE url = "'.$url.'"';
$fparam = array( 'method' => 'fql.query', 'query' => $fquery );
$fql = $facebook->api($fparam);
$cmcount = $fql[0]['comment_count'];
So, $cmcount is now your comment counts, put it directly in your html code:
<div id="comments">
<?php echo $cmcount; ?>
</div>

Related

I am trying to get a list of pages i admin on facebook using the graphapi

I am following the example
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.2
I have this working and I can get the user..
FacebookSession::setDefaultApplication(FB_APP_ID,FB_APP_SECRET);
$helper = new FacebookRedirectLoginHelper( 'http://localhost:8088' );
$session = new FacebookSession( $_SESSION['fb_access_token'] );
if ( isset( $session ) ) {
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
$user = $response->getGraphObject(GraphUser::className());
Now i need to do a fql and i am unsure how to the $facebook object??
$fql = 'SELECT name,page_id FROM page WHERE page_id IN
(SELECT page_id FROM page_admin WHERE uid='.$user->getID() .')';
$ret_obj = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql,
));
Thanks
Don't use FQL. It been deprecated and will stop working. Use the Graph API instead and do /me/accounts as explained at https://developers.facebook.com/docs/graph-api/reference/v2.2/user/accounts

Modify facebook like button

At this moment "like" button works just with facebook groups. I want to implement "like" button to my website and let people to like photos of my site. It is possible to do it? Or how to programically like facebook photos?
You can like any object, including a photo object by issuing a post to its object url, after receiving proper permissions " publish_stream". Deleting the like is same, just issue 'delete' instead of 'post'
https://developers.facebook.com/docs/reference/api/photo/#likes
Using php sdk 3.1.1, with user access token you can :
-----publish like----- this will post a like to the photos like object.
<?php
$params = array(
'access_token' => ''.$access_token.'',
'method' => 'post'
);
$pageLike = $facebook->api('/PhotoID/likes', 'post', $params);
?>
-----issue delete----- this will delete a like to the photos like object.
<?php
$params = array(
'access_token' => ''.$access_token.'',
'method' => 'post'
);
$pageLike = $facebook->api('/PhotoID/likes', 'delete', $params);
?>

Asking for facebook permissions only when required

I have the following script which works, i.e. it goes to the facebook login page if the user is not already logged in, and asks them if they are ok with the app to post messages on their wall:
<?php
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'removed for security reasons',
'secret' => 'removed for security reasons',
'cookie' => true,
));
$session = $facebook->getSession();
if ($session) {
if (isset($_GET[id])) {
$post = $facebook->api("/" . $_GET['id'] . "/feed", "POST", array('message' => 'Hello!'));
echo 'A message has been posted on your friends wall';
} else {
$friends = $facebook->api('/me/friends');
foreach ($friends as $key=>$value) {
echo 'You have ' . count($value) . ' friends<br />';
foreach ($value as $fkey=>$fvalue) {
echo 'friend id = ' . $fvalue[id] . ' - friend name = ' . $fvalue[name] . ' - post message<br />';
}
}
}
} else {
$loginUrl = $facebook->getLoginUrl(array(
'req_perms' => 'publish_stream',
'next' => 'http://'.$_SERVER['SERVER_NAME'].'/stage1.php',
'cancel_url' => 'http://'.$_SERVER['SERVER_NAME'].'/cancel.php',
));
header('Location: '.$loginUrl);
}
?>
How can this be improved so it does not ask for extended permissions in the start. It should only ask for basic permissions to display the friends list, and only ask for extended permissions if the user clicks on the friend to post a message.
Here's a rewrite of your code, with what I think are best practices:
<?php
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'removed for security reasons',
'secret' => 'removed for security reasons',
'cookie' => true,
));
$session = $facebook->getSession();
// Prepare the login url with the right permission
$loginUrl = $facebook->getLoginUrl(array(
'req_perms' => 'publish_stream',
'next' => 'http://'.$_SERVER['SERVER_NAME'].'/stage1.php',
'cancel_url' => 'http://'.$_SERVER['SERVER_NAME'].'/cancel.php',
));
if ($session) {
try {
// Before processing the request
// check if we got the right permission
$perms = $facebook->api(array(
"method" => "fql.query",
"query" => "SELECT publish_stream FROM permissions WHERE uid=me()"
));
if($perms[0]['publish_stream']==='1') {
// We have the right permission
if (isset($_GET['id'])) {
// A small security measure
$id = (int) $_GET['id'];
$post = $facebook->api("/$id/feed", "POST", array('message' => 'Hello!'));
echo 'A message has been posted on your friends wall';
} else {
$friends = $facebook->api(array(
"method" => "fql.query",
"query" => "SELECT uid,name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me())"
));
foreach($friends as $friend)
echo "friend id = {$friend['uid']} - friend name = {$friend['name']} - post message<br />";
}
} else {
// We don't have the right permission
header('Location: '.$loginUrl);
}
} catch (FacebookApiException $e) {
error_log($e);
}
} else {
header('Location: '.$loginUrl);
}
?>
How to check for a permission is explained here. Also I've added comments to save writing an explanation.
Quickly, there is something I want to point out regarding the following block of code:
foreach ($friends as $key=>$value) {
echo 'You have ' . count($value) . ' friends<br />';
foreach ($value as $fkey=>$fvalue) {
echo 'friend id = ' . $fvalue[id] . ' - friend name = ' . $fvalue[name] . ' - post message<br />';
}
}
Your 1st foreach loop is really misleading and not good practice at all. The Graph API isn't overly consistent in how it presents data, but the reason you are doing the foreach is to deal with the data key in the JSON object that is returned. This is generally a bad idea, because that data key is typically present along with other keys (like paging). Instead, I would check to see that $friends['data'] is not empty, and then re-assign the $friends array like so: $friends = $friends['data'];.
Example:
if (!empty($friends['data']))
{
$friends = $friends['data'];
}
else
{
$friends = array();
}
now, for your question.
You mentioned that you don't want to over-ask for permissions. That's a great thing to want, but the problem with it is that Facebook doesn't make it exceedingly easy to check for which permissions you do have or do not have. There is an FQL table that allows you check if your user has a certain set of permissions, but this table doesn't get updated with any kind of urgency. If you obtain extra permissions from a user (or if a user retracts permissions) and you then check this FQL table for the status of the permission, it can (and probably will) read the incorrect value and you will get a false positive.
You have three options to deal with this, that I can think of right off the top of my head.
Continue on your stage1.php code, as you are - there's nothing wrong with the way you're obtaining the installation and the session for the user there. You change page 2 to redirect your user through the OAuth endpoint requesting the publish-stream permission every time the user loads the page. The OAuth endpoint will not re-prompt the user to install, and will send them on their way.
The cons with this approach is, every request to post to a friends' wall turns into 3 requests.
The initial page load
The OAuth redirect / load
The redirect from OAuth back to your application
This approach also requires that you add a flag to your next key in your loginURL, which you can look for to make sure the user went through the OAuth endpoint, otherwise you're going to get an infinite redirect error.
Utilize the FB Javascript SDK to check for your users' current set of permissions. To do this, you'll utilize the FB.getLoginStatus method.
Example:
<div id="fb-root"></div>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"
type="text/javascript" charset="utf-8">
</script>
<script src="http://connect.facebook.net/en_US/all.js"
type="text/javascript" charset="utf-8">
</script>
<script type="text/javascript">
(function($)
{
FB.init({
appId: '<?= FB_APP_ID; ?>',
cookie: true,
status: true,
xfbml: true
});
$('a').click(function(event)
{
var self = this;
event.preventDefault();
FB.getLoginStatus(function(session)
{
if (session.perms.match(/\"publish_stream\"/))
{
/* This user has publish stream, so we don't need
* to ask again
**/
window.location = $(self).attr('href');
}
else
{
/* This user does not have publish stream, so we need
* to ask.
**/
FB.login(function(response)
{
if (response && response.perms.match(/publish_stream/))
{
/* We now have publish stream access! */
window.location = $(self).attr('href');
}
}, {
perms: 'publish_stream'
});
}
})
return false;
})
})(jQuery);
Don't utilize any extended permissions, use the Javascript SDK (again) and give the user a publish-dialog for each user they would like to publish on the wall of. This is a relatively easy thing to do, also.
Example:
given your links for users:
Friend 1
Friend 2
Friend 3
You can do something like this:
<div id="fb-root"></div>
<script src="http://code.jquery.com/jquery-1.5.2.min.js"
type="text/javascript" charset="utf-8">
</script>
<script src="http://connect.facebook.net/en_US/all.js"
type="text/javascript" charset="utf-8">
</script>
<script type="text/javascript">
(function($)
{
$('a').click(function(event)
{
var user_id = $(this).data('id');
FB.ui({
method: 'feed',
message: 'Hello!',
to: user_id
}, function(response)
{
//this gets called whether it was successful, or not.
})
});
})(jQuery);

How to use Facebook's FQL query using graph API?

Is there a way to use Facebook's FQL query using the current graph API? Or we still have to use the legacy API?
Example of Graph API and JavaScript:
FB.api(
{
method: 'fql.query',
query: 'SELECT uid, first_name, last_name FROM user WHERE uid = ' + someUid
},
function(data) {
// do something with the response
}
);
http://developers.facebook.com/docs/reference/javascript/
http://developers.facebook.com/docs/reference/fql/
Example Of Rest API:
$data = $facebook->api( array( 'method' => 'fql.query', 'query' => 'SELECT shit FROM table...' ) );

how to use fql query

i am new at facebook application development i want to know how fql query works i used it in my application but i want to know where fql query results are displayed or how they can be displayed if you can't explain plz send me the link because the official documentation didn't helped me either.
Connect to FB using the PHP SDK. (available here)
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once 'library/facebook/src/facebook.php';
Check if the user has logged in to FB
$facebook = new Facebook(array(
'appId' => 'YOUR API ID',
'secret' => 'YOUR APP SECRET',
'cookie' => true, // enable optional cookie support
));
FQL
try {
$me = $facebook->api('/me');
$currentPage=1;
$currentPost=1;
$currentDate="";
$list="";
$arrDate=array();
$fql = "YOUR FQL STATEMENT HERE";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);//Here you have your FQL result set
foreach($fqlResult as $row){
//Do something to the result
}
} catch (FacebookApiException $e) {
error_log($e);
}
You can use the Facebook Graph Explorer
https://developers.facebook.com/tools/explorer
And select under the Access token field, "FQL query".
Now you can try FQL queries and see the result of them.