Feeds in Facebook Applications

Exclusive offer: get 50% off this eBook here
Learning Facebook Application Development

Learning Facebook Application Development — Save 50%

A step-by-step tutorial for creating custom Facebook applications using the Facebook platform and PHP

$23.99    $12.00
by Dr Mark Alexander Bain Hasin Hayder | July 2009 | MySQL Open Source PHP

Feeds are a very important part of Facebook Applications. They are used to publish notifications and news in a user's profile. So, feeds are the best way to keep the friends of the users up-to-date about the user's current activities. Feeds are also a great way to publicize your applications, if you know what I mean.

In this article by Dr. Mark Alexander Bain and Hasin Hayder, we will go into the details of managing feeds (both news feed and mini feed) using Facebook REST APIs. The following sections will help you understand what the major differences between these two types of feed are, and how to use them properly in your application.

{literal}

What Are Feeds?

Feeds are the way to publish news in Facebook. As we have already mentioned before, there are two types of feeds in Facebook, News feed and Mini feed. News feed instantly tracks activities of a user's online friends, ranging from changes in relationship status to added photos to wall comments. Mini feed appears on individuals' profiles and highlights recent social activity. You can see your news feed right after you log in, and point your browser to http://www.facebook.com/home.php. It looks like the following, which is, in fact, my news feed.

Feeds in Facebook Applications

Mini feeds are seen in your profile page, displaying your recent activities and look like the following one:

Feeds in Facebook Applications

Only the last 10 entries are being displayed in the mini feed section of the profile page. But you can always see the complete list of mini feeds by going to http://www.facebook.com/minifeed.php. Also the mini feed of any user can be accessed from http://www.facebook.com/minifeed.php?id=userid.

There is another close relation between news feed and mini feed. When applications publish a mini feed in your profile, it will also appear in your friend's news feed page.

How to publish Feeds

Facebook provides three APIs to publish mini feeds and news feeds. But these are restricted to call not more than 10 times for a particular user in a 48 hour cycle. This means you can publish a maximum of 10 feeds in a specific user's profile within 48 hours. The following three APIs help to publish feeds:

  • feed_publishStoryToUser—this function publishes the story to the news feed of any user (limited to call once every 12 hours).
  • feed_publishActionOfUser—this one publishes the story to a user's mini feed, and to his or her friend's news feed (limited to call 10 times in a rolling 48 hour slot).
  • feed_publishTemplatizedAction—this one also publishes mini feeds and news feeds, but in an easier way (limited to call 10 times in a rolling 48 hour slot).

You can test this API also from http://developers.facebook.com/tools.php?api, and by choosing Feed Preview Console, which will give you the following interface:

Feeds in Facebook Applications

And once you execute the sample, like the previous one, it will preview the sample of your feed.

Sample application to play with Feeds

Let's publish some news to our profile, and test how the functions actually work. In this section, we will develop a small application (RateBuddies) by which we will be able to send messages to our friends, and then publish our activities as a mini feed. The purpose of this application is to display friends list and rate them in different categories (Awesome, All Square, Loser, etc.).

Here is the code of our application:

index.php

<?
include_once("prepend.php"); //the Lib and key container
?>
<div style="padding:20px;">
<?
if (!empty($_POST['friend_sel']))
{
$friend = $_POST['friend_sel'];
$rating = $_POST['rate'];
$title = "<fb:name uid='{$fbuser}' useyou='false' /> just <a href='http://
apps.facebook.com/ratebuddies/'>Rated</a> <fb:name uid='{$friend}' useyou='false' />
as a '{$rating}' ";
$body = "Why not you also <a href='http://apps.facebook.com/
ratebuddies/'>rate your friends</a>?";

try{
//now publish the story to user's mini feed and on his friend's news feed
$facebook->api_client->feed_publishActionOfUser($title, $body,
null, $null,null, null, null, null, null, null, 1);
} catch(Exception $e) {
//echo "Error when publishing feeds: "; echo $e->getMessage();
}
}
?>
<h1>Welcome to RateBuddies, your gateway to rate your friends</h1>
<div style="padding-top:10px;">
<form method="POST">
Seect a friend: <br/><br/>
<fb:friend-selector uid="<?=$fbuser;?>" name="friendid"
idname="friend_sel" />
<br/><br/><br/>
And your friend is: <br/>
<table>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="funny" /></td>
<td valign="middle">Funny</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="hot tempered" /></td>
<td valign="middle">Hot Tempered</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="awesome" /></td>
<td valign="middle">Awesome</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="naughty professor" /></td>
<td valign="middle">Naughty Professor</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="looser" /></td>
<td valign="middle">Looser</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="empty veseel" /></td>
<td valign="middle">Empty Vessel</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="foxy" /></td>
<td valign="middle">Foxy</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="childish" /></td>
<td valign="middle">Childish</td>
</tr>
</table>
&nbsp; <input type="submit" value="Rate Buddy"/>
</form>
</div>
</div>


index.php includes another file called prepend.php. In that file, we initialized the facebook api client using the API key and Secret key of the current application. It is a good practice to keep them in separate file because we need to use them throughout our application, in as many pages as we have. Here is the code of that file:

prepend.php

<?php
// this defines some of your basic setup
include 'client/facebook.php'; // the facebook API library
// Get these from ?http://www.facebook.com/developers/apps.php
http://www.facebook.com/developers/apps.php$api_key = 'your api
key';//the api ket of this application
$secret = 'your secret key'; //the secret key

$facebook = new Facebook($api_key, $secret);
//catch the exception that gets thrown if the cookie has an invalid
session_key in it
try {
if (!$facebook->api_client->users_isAppAdded()) {
$facebook->redirect($facebook->get_add_url());
}
} catch (Exception $ex) {
//this will clear cookies for your application and redirect them
to a login prompt
$facebook->set_user(null, null);
$facebook->redirect($appcallbackurl);
}
?>

The client is a standard Facebook REST API client, which is available directly from Facebook.

If you are not sure about these API keys, then point your browser to http://www.facebook.com/developers/apps.php and collect the API key and secret key from there. Here is a screenshot of that page:

Feeds in Facebook Applications

Just collect your API key and Secret Key from this page, when you develop your own application.

Now, when you point your browser to http://apps.facebooks.com/ratebuddies and successfully add that application, it will look like this:

Feeds in Facebook Applications

To see how this app works, type a friend in the box, Select a friend, and click on any rating such as Funny or Foxy. Then click on the Rate Buddy button. As soon as the page submits, open your profile page and you will see that it has published a mini feed in your profile.

Feeds in Facebook Applications

Learning Facebook Application Development A step-by-step tutorial for creating custom Facebook applications using the Facebook platform and PHP
Published: May 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

 

So How Did it Work?

We have used the following code for the friend selector. It takes three parameters. The uid is the currently logged in user's id whose friend list will be rendered. For choosing friends, the second one is name, which will act as the POST field name when the user submits it. This field will contain the name of the chosen friend. The third parameter is the POST field name that will hold the chosen friend's id.

<fb:friend-selector uid="<?=$fbuser;?>" name="friendid" 
idname="friend_sel" />

So after submitting, you will get the friend's id and name as $_POST['friend_sel'] and $_POST['friendid'].

Now take a look at the following PHP code that publishes the mini feed:

<?
if (!empty($_POST['friend_sel']))
{
$friend = $_POST['friend_sel'];
$rating = $_POST['rate'];
$title = "<fb:name uid='{$fbuser}' useyou='false' /> just <a
href='http://apps.facebook.com/ratebuddies/'>Rated</a> <fb:
name uid='{$friend}' useyou='false' /> as a '{$rating}' ";
$body = "Why not you also <a href='http://apps.facebook.com/
ratebuddies/'>rate your friends</a>?";
try{
$facebook->api_client->feed_publishActionOfUser($title, $body,
null, $null,null, null, null, null, null, null, 1);
} catch(Exception $e) {
echo "Error when publishing feeds: "; echo $e->getMessage();
}
}
?>

It uses the FBML tags to render the user's name and uses feed_publishActionOfUser() API to publish the news feed.

Please note that you can only use <fb:name/>, <fb:link/>,<a>,<b>, and <i> tag in mini feed's body. And in title, you can only use <fb:name/>, <fb:link/>, and <a> tag. If you use any other tag, they will be stripped by Facebook along with the enclosed content.

There is no guarantee that the mini feed will also be published in your friend's news feed. It may or may not be published based on their news feed settings and the competing stories.

Publishing News Feed

Let's add more functionality to our application. We want to enable news feeds in the personal news feed section, which will tell you how many of your friends have been rated in the last 12 hours. If there is any, you will be able to see them in your news feed.

For this, we need to use a database with our application, which will contain the time of rating and the ids of both the users who rate, and the users who are rated. We will also store the given rating. Let's do it. Here is our table schema.

Table Rates

Feeds in Facebook Applications

Now let's take a look at the revised code of our index.php:

<?
include_once("prepend.php");
mysql_pconnect($dbhost, $dbuser, $dbpwd);
mysql_select_db($dbname);
?>
<div style="padding:20px;">
<?
if (!empty($_POST['friend_sel']))
{
$time = time();
$friend = $_POST['friend_sel'];
$rating = $_POST['rate'];
mysql_query("INSERT INTO rates (id, sender, receiver,rating,
`time`) VALUES (null,{$fbuser},{$friend},'{$rating}',{$time})");
$title = "<fb:name uid='{$fbuser}' useyou='false' /> just <a href='http://
apps.facebook.com/ratebuddies/'>Rated</a> <fb:name uid='{$friend}' useyou='false' />
as {$rating}.";
$body = "Why not you also <a href='http://apps.facebook.com/
ratebuddies/'>rate your friends</a>?";
try{
$facebook->api_client->feed_publishActionOfUser($title, $body,
null, $null,null, null, null, null, null, null, 1);
} catch(Exception $e) {
echo "Error when publishing feeds: "; echo $e->getMessage();
}
}
//search for friends who have been rated in last 12 hours where sender
is not you and receiver is any of your friends
$friends = $facebook->api_client->friends_get();
$temp = join(",",$friends);

$checkpoint = time()-12*60*60;
$result = mysql_query("SELECT * FROM rates WHERE `time`>{$checkpoint}
AND sender != {$fbuser} AND receiver IN ($temp)");
if (mysql_num_rows($result)>0)
{
$info = $facebook->api_client->users_getInfo($friends,array("uid",
"name"));
$friendsname = array();
foreach ($info as $_temp)
{
$friendsname[$_temp['uid']] = $_temp['name'];
}
$report = "";
while ($data = mysql_fetch_assoc($result))
{
$report .= "<a href='http://www.facebook.com/profile.php?id={
$data['sender']}'>{$friendsname[$data['sender']]}</a> just rated <a
href='http://www.facebook.com/profile.php?id={$data['receiver']}'>
{$friendsname[$data['receiver']]}</a> as {$data['rating']}. ";
}
$newstitle = "Friends recently rated...";
try{
$facebook->api_client->feed_publishStoryToUser($newstitle, $report,
null, $null,null, null, null, null, null, null, 1);
} catch(Exception $e) {
// echo "Error when publishing feeds: ";
echo $e->getMessage();
}
}
?>
<h1>Welcome to RateBuddies, your gateway to rate your friends</h1>
<div style="padding-top:10px;">
<form method="POST">
Seect a friend: <br/><br/>
<fb:friend-selector uid="<?=$fbuser;?>" name="friendid"
idname="friend_sel" />
<br/><br/><br/>
And your friend is: <br/>
<table>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="funny" /></td>
<td valign="middle">Funny</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="hot tempered" /></td>
<td valign="middle">Hot Tempered</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="awesome" /></td>
<td valign="middle">Awesome</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="all sqaure" /></td>
<td valign="middle">All Square</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="naughty professor" /></td>
<td valign="middle">Naughty Professor</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="looser" /></td>
<td valign="middle">Looser</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="empty veseel" /></td>
<td valign="middle">Empty Vessel</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="foxy" /></td>
<td valign="middle">Foxy</td>
</tr>
<tr>
<td valign="middle"><input name="rate" type="radio"
value="childish" /></td>
<td valign="middle">Childish</td>
</tr>
</table>
&nbsp; <input type="submit" value="Rate Buddy"/>
</form>
</div>
</div>

So how is it working? Once somebody rates his or her friends, we store the result in our table using the following code:

if (!empty($_POST['friend_sel']))
{
$time = time();
$friend = $_POST['friend_sel'];
$rating = $_POST['rate'];
mysql_query("INSERT INTO rates (id, sender, receiver,rating,
`time`) VALUES (null,{$fbuser},{$friend},'{$rating}',{$time})");
echo "INSERT INTO rates (id, sender, receiver,
`time`) VALUES (null,{$fbuser},{$friend},{$time})";
echo mysql_error();

Now, comes the tricky part. We need to retrieve all the friends of the currently logged in user who had been rated in the last 12 hours. But we must keep in mind that we will not pick those who are not rated by the logged in user, but someone else. We'll do it using the following code:

$friends = $facebook->api_client->friends_get();
$temp = join(",",$friends);
$checkpoint = time()-12*60*60;
$result = mysql_query("SELECT * FROM rates WHERE `time`>{$checkpoint}
AND sender != {$fbuser} AND receiver IN ($temp)");

It will give you friends that you have rated in the last 12 hours.

Here's another tricky part. While publishing the mini feed, we displayed the names of our friends using the <fb:name> tag, which is not supported in news feeds. So we must find another way to display their names. We'll fetch all the friend's names using users_getInfo() API and store them in a temporary array. Later, we'll use that array to display the names. Finally, we'll publish the news feed. Look at the following code:

if (mysql_num_rows($result)>0)
{
$info = $facebook->api_client->users_getInfo($friends,array
("uid","name"));
$friendsname = array();
foreach ($info as $_temp)
{
$friendsname[$_temp['uid']] = $_temp['name'];
}
$report = "";
while ($data = mysql_fetch_assoc($result))
{
$report .= "<a href='http://www.facebook.com/profile.php?id=
{$data['sender']}'>{$friendsname[$data['sender']]}</a> just rated
<a href='http://www.facebook.com/profile.php?id={$data['receiver']}'>
{$friendsname[$data['receiver']]}</a> as {$data['rating']}. ";
}
$newstitle = "Friends recently rated...";
try{
$facebook->api_client->feed_publishStoryToUser($newstitle, $report,
null, $null,null, null, null, null, null, null, 1);
} catch(Exception $e) {
// echo "Error when publishing feeds: "; echo $e->getMessage();
}
}

So how would the output look like? You are definitely thinking about it, right? Have a look:

Feeds in Facebook Applications

Difference between These Two Methods

There are significant differences between feed_publishStoryToUser() and feed_publishActionOfUser() functions. The Facebook Wiki has a comprehensive list of key differences at http://wiki.developers.facebook.com/index.php/PublishActionOfUser_vs._PublishStoryToUser, which is worth giving a look.

Feeds in Facebook Applications

Besides the above, each of these functions has the following restrictions:

  • Title length is limited to 60 characters (excluding tags).
  • Body length is limited to 200 characters (excluding tags).
  • Included images must have an associated link.
  • The associated image links must be http links. Notably, https links do not work.

feed_publishTemplatizedAction

This is another API to publish news feed to a friend of the user. It helps developers to be more structured. This function takes a number of parameters, and all the rules of publisActionOfUser are affected by the same kind of uncertainty and delay that is encountered while publishing the feed. Spam and server load are the major factors for that.

If you take a look at the definition of this API, you will find the following:

Learning Facebook Application Development A step-by-step tutorial for creating custom Facebook applications using the Facebook platform and PHP
Published: May 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Param

Description

 

title_template

A template which contains the title of the feed

 

title_data

A JSON encoded string containing the value of the template variables

 

body_template

 

Template containing the text of the body

 

body_data

 

A JSON encoded string containing the value of the template variables

body_general

 

Additional template data to include in the body

image_1

 

The URL of an image to be displayed in the Feed story

image_1_link

 

The URL destination after a click on the image referenced by image_1

image_2

 

The URL of an image to be displayed in the Feed story

image_2_link

 

The URL destination after a click on the image referenced by image_2

image_3

 

The URL of an image to be displayed in the Feed story

image_3_link

 

The URL destination after a click on the image referenced by image_3

image_4

 

The URL of an image to be displayed in the Feed story

image_4_link

 

The URL destination after a click on the image referenced by image_4

target_id

 

Comma-delimited list of IDs of friends of the actor, used for stories about a direct action between the actor and these targets of his/her action. This is required if either the title_template or body_template includes the token {target}.

 

 

 

 

 

 

This API can publish up to four images in the feed. You can also make them clickable by supplying the destination URL along with them. Let's have a look at the following code, which will show you how to use this API. After a specific event in your application, you can use code like the following one:

<?php
$titleTemplate + "{actor} gifts a
{item} to {friend}";
$titleData =
array("item"=>"flower","friend"=>"<fb:name
uid='some
uid'>");

$bodyTemplate =
"color of that {item} is {color}";
$bodyData =
array("color"=>"red","item"=>"flower");

$image1
= "absolute url of an image";
$image1Target = "target url when
clicked over that
image";

$facebook->api_client->feed_publishTemplatizedAction($titleTemplate,j
son_encode($titleData),$bodyTemplate,json_encode($bodyData),$image1,$
image1Target);
?>

There are some default values, which are replaced by Facebook itself, while publishing the feed. For example the value of actor in the above feed will always be replaced as the viewer or currently logged in user. There is a fantastic article on this API and you are encouraged to read it.

http://facebook-developer.net/2008/01/21/how-to-successfully-publish-
widespread-news-feed-stories/

Summary

News feed and mini feeds are a very important part for delivering news to the users of your applications, and keep their friends up-to-date about the activities. In this article, we have learnt how to deal with Feed APIs provided by Facebook. We have also learnt the major difference between these APIs and their usage.

About the Author :


Dr Mark Alexander Bain

Dr. Mark Alexander Bain first started customizing CRM systems back in the mid '90s when he was team leader for Vodafone's Cascade project – the team took the 'out-of-the-box' Clarify CRM and turned it into a radio base station planning application, complete with a workflow engine for passing jobs between the different departments involved in the planning, building, and implementation of a radio network. Since then he's lectured at the University of Central Lancashire, and currently Mark writes articles on all things Linux and Open Source for Linux Format, Newsforge.com and Linux Journal. SugarCRM customization, therefore, seems the obvious choice for this, his second book, since it combines Mark's knowledge of working with commercial CRMs and the Open Source philosophy. Mark works from his home on the edge of the Lake District in the UK, where he lives with his wife, two dogs and two cats, and gets the odd visit from his sons – Michael and Simon.

Hasin Hayder

Hasin Hayder graduated in Civil Engineering from the Rajshahi University of Engineering and Technology (RUET) in Bangladesh. He is a Zend-certified Engineer and expert in developing localized applications. He is currently working as a Technical Director in Trippert Labs and managing the local branch in Bangladesh. Beside his full time job, Hasin writes his blog at http://hasin.wordpress.com, writes article in different websites and maintains his open source framework Orchid at http://orchid.phpxperts.net. Hasin lives in Bangladesh with his wife Ayesha and his son, Afif.

Books From Packt

Drools JBoss Rules 5.0 Developer's Guide
Drools JBoss Rules 5.0 Developer's Guide

Plone 3 Theming
Plone 3 Theming

WordPress 2.7 Cookbook
WordPress 2.7 Cookbook

Building Enterprise Ready Telephony Systems with sipXecs 4.0
Building Enterprise Ready Telephony Systems with sipXecs 4.0

PHP and script.aculo.us Web 2.0 Application Interfaces
PHP and script.aculo.us Web 2.0 Application Interfaces

Expert Cube Development with Microsoft SQL Server 2008 Analysis Services
Expert Cube Development with Microsoft SQL Server 2008 Analysis Services

WordPress 2.7 Complete
    WordPress 2.7 Complete

Drupal 5 Views Recipes
Drupal 5 Views Recipes

Your rating: None Average: 4 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
B
s
A
Y
j
S
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software