Archive for February, 2009

how to resize facebook popup dialog box

while developing facebook applications, sometimes we don’t like to use the default facebook popup dialog box, we want to resize/modify to show it on our own way. but how can we do it? we don’t have the css class on our hand right. but don’t worry, we have this simple trick to make it on our own way.

let’s see how we can do it….

first let’s see how a default popup box looks like. let’s print something pretty simple and set a button that will call the javascript function which will create the default popup dialog box. following code will do it for us..

<?php
include_once("config.php");
?>
<input type="button" value="click me" onclick=" return showMe()">
<script language="javascript">
function showMe()
{
   new Dialog().showMessage('Hi There', ' Hi, i\'m a default pop-up, but shh you can play with me!' );
}
</script>

and this will generate a popup like the following screen shot.

Default Dialog Box

Default Dialog Box

now, we want to change this default dialog box right. ok, this default dialog box uses some css classes which can be found using firefox add on firebug. one of them is called “dialog_body” which contains the body of the dialog box. Idea is to overwrite the css class to make it our own :) let’s change the “dialog_body” class in the following way…


<style>
.dialog_body{
   background-color:#CCCCCC !important;
   font-weight:bold !important;
   font-size:16px;
   text-align:center !important;
   padding-left:0px !important;
   padding-top:10px!important;
   padding-bottom:10px!important;
}
</style>

just set the “!important” to get the priority over the existing properties. now let’s see how out new dialog box looks like ..

Changed Dialog Box

Changed Dialog Box

cool eh?
now, how about make this popup dialog box wider than the default size? well, we have that trick too!
this css class called “pop_dialog_table“, which holds the whole dialog box’s div. so increasing it’s width will also increase the size of the dialog box. so let’s do it!


<style>
.pop_dialog_table {
   width: 650px !important;
}
</style>

how this will look like then? have a look at the following screen shot

Wider Dialog Box

Wider Dialog Box

simple eh? hope it helps to play with this popup dialog box on your own way!

how to keep track of users of your application, and how to remove them properly when they remove it

there are two things we are going to discuss in this article. both of these are very important issues for successful marketing of your app, to generate precise traffic report. and if you want to sell your app or generate revenue, traffic report is very important. so we are going to show you how to maintain a precise list of your active users and how to precisely remove them when they remove your app.

keeping track of your users
this one is fairly easy. but beside storing their user id you should keep track of their session ids. why? for extended permissions and for viral marketing. lets create a mysql table for storing these data, along with the active/inactive


+------------+---------------------+------+-----+---------+-------+
| Field      | Type                | Null | Key | Default | Extra |
+------------+---------------------+------+-----+---------+-------+
| uid        | bigint(20) unsigned | NO   | PRI |         |       |
| sessionkey | varchar(128)        | YES  |     | NULL    |       |
| active     | char(1)             | YES  | MUL | 1       |       |
+------------+---------------------+------+-----+---------+-------+

here is the SQL


CREATE TABLE `users` (
  `uid` bigint(20) unsigned NOT NULL,
  `sessionkey` varchar(128) default NULL,
  `active` char(1) default '1',
  PRIMARY KEY  (`uid`),
  KEY `activity` (`active`)
)

now can you remember that there is a field named “Post authorize redirect url” in the “Authentication” tab of your application settings page? set the data in that field before proceeding further. have a look at the following screenshot. you can see it’s enlarged view by clicking on it

picture-7

now lets see how to store the user ids and their corresponding session key. in the following code block there are two functions for storing user ids in your database and for updating their session key.


<?php
/**
 * insert a new user and corresponding session key in the users table
 *
 * @param int $uid user id
 * @param string $sk session key
 * @param resource $db mysql connection resource
 * @return bool
 */
function insertUser($uid,$sk,$db)
{
    $data= mysql_query("select uid from users where uid='{$uid}'",$db);
    if(mysql_num_rows($data)==0)
    {
        $sql = "INSERT INTO users (uid,sessionkey, active) VALUES('{$uid}','{$sk}','1')";
        mysql_query($sql,$db);
        return true;
    }
    return false;
}

/**
 * update an user's corresponding session key in users table
 *
 * @param int $uid user id
 * @param string $sk session key
 * @param resource $db mysql connection resource
 * @return bool
 */
function updateSessionKey($uid,$sk,$db)
{
   return mysql_query("update users set sk = '{$sk}' where uid='{$uid}",$db);
}

?>

now in your install.php all you have to do is place the following code.


include_once("config.php");
$sk = $facebook->api_client->session_key;

$db = mysql_connect('host','user','db');
mysql_select_db("db",$db);

insertUser($uid,$sk, $db);
echo "<fb:redirect url='YourApplicationUrl' />";

thats it. now you can periodically update your user’s session key to stay uptodate using updateSessionKey() function.

how to remove your user
remember in the previous screenshot there was a field named “Post-Remove Callback URL” in the application setup page? when any of your application users remove this application from their account, facebook sends some information to this callback url so that you, the application developer, can successfully take necessary steps to remove this user from your database or set the inactive flag “ON”. lets see how to do this. here is the code of “remove.php”


<?php
include_once("config.php");
$facebook = new Facebook($apikey, $secret);
$user = $facebook->get_loggedin_user();
if ($user != NULL &amp;amp;&amp;amp; $facebook->fb_params['uninstall'] == 1)
{
    makeUserInactive($uid,$db); //$db is your mysql link indentifier
}

/**
 * set an user as inactive, indicating that user has removed your application
 *
 * @param int $uid user id
 * @param resource $db mysql connection resource
 * @return bool
 */
function makeUserInactive($uid,$db)
{
    return mysql_query("update users set active = '0' where uid='{$uid}",$db);
}
?>

thats it! for reference you can check out facebook wiki entry.

updating profile box using <fb:ref />

<fb:ref is a new fbml tag used to store data and later re-use it. there are two types of ref handler, one is static and another is url based. lets have a look at their structure

1. string handle which just stores FBML and later output the content – like


<fb:ref handle="application_specific_unique_handle" />

or

2. url based, which must serve valid FBML


<fb:ref url="some_url" />

you can create <fb:ref /> by using fbml_setRefHandle() function. now lets see <fb:ref />s in action. the following code will create a <fb:ref /> and you can later use it anywhere in your application. remember, once created the ref objects are in application scope. and until you change the content again using fbml_setRefHandle() api, it will remain the same.


<?php
include "config.php";
$handle = "greetings";
$markup = "Hello <fb:name uid='{$uid}' /> ";
$facebook->api_client->fbml_setRefHandle($handle, $markup);
?>

now you can use it anywhere in your application like this


<fb:ref handle="greetings" />

it will say "Hello <User’s Name>"

but wait, there is a major disadvantage with this type of handlers and that is the content of this ref object is cached. say, while creating the ref object if the $uid was, for example 503274632 (which is my id) – when I will come to a page that used this "greetings" ref object, I will see that the out put is "Hello you" and that is expected. Now when another user see the same page he will see that the output is "Hello Hasin Hayder", but this was not expected. Look, here it didn’t update the content according to the new user. Because the content of this ref object will remain cached until u change it again using fbml_setRefHandle() api.

to over come this problem and to make these ref objects more usable, you can use url type ref objects. lets see below, you have to use fbml_refreshRefUrl() api.


<?php
include "config.php";
$url = "http://sandbox.ofhas.in/fbtest/ru.php?uid={$uid}";
$facebook->api_client->fbml_refreshRefUrl($url);
?>

and the content of ru.php is


Hello from an external Url <fb:name uid="<?=$_REQUEST['uid'];?>" useyou="false" />

now you can use this url type ref object anywhere in your application, like this


Greetings! <fb:ref url="<?=$url;?>" />

now if you want to update content of your user’s profile box offline. Just print any url type ref handler in his profile box using profile_setFBML() api. later, on the time of updating all you have to do is call fbml_refreshRefUrl() so that facebook re cache the content of this url. and regardless to say that your url will deliver all the updated content to display on yoru profiles. your url will always get the user id via “uid” parameter in HTTP GET, so you can decide easily what to deliver.

if you are still confused or have any question, don’t forget to write it as a comment. in next article I am coming with “how to successfully keep record of all the users of your applications and how to remove them successfully when they remove your app” – stay tuned.

how to add profile tab for your facebook application

in new facebook design, users can add an application tab in their profile page along with 4 default tabs Wall, Infos, Photos & Boxes. In this tutorial we will see how we can add profile tab for our facebook application.
so, let’s go through couple of simple steps that will get this process done.
first of all, let’s keep something in our mind before we jump into it.

  • an application tab is 760 pixels wide. You can make your canvas pages as wide as an application tab if you want.
  • each application tab has a label. The labels are text only; a favicon cannot appear on the tab label at this time. by default, the tab uses the application name as the label

now, you have to register an application tab on facebook by specifying a tab URL in your application settings. go to your application settings> Edit Settings, from left nav select “User Profiles” – you there right? In the tab name, give something easy and related to your application name so that user can find it by search. In the second row, you are supposed to see “Tab URL”. In the box just enter a name of your page or the location (i.e. my_tab.php)

save the change and close the window. now create a new page called “my_tab.php”. open the page in your favorite IDE. now, let’s print something pretty simple to make sure our tab is working fine. you can print anything you want or you can copy & paste the following peace of code to see something on your tab page.


<?php $user = $_POST['fb_sig_profile_user'];
?>
hi <fb:name uid=<?=$user;?> linked='true' size='normal' useyou='false' firstnameonly='false'/>, glad to see your profile tab is working!

now, there is a common problem for those who added their profile tab before, they are getting this following message, although it worked before.
fb:redirect: redirect forbidden by flavor TabFBMLFlavor on the profile tab.
you are facing the same problem? Don t worry at all. Just check if you have this require log in in your profile tab page
i.e.:

  $user = $facebook->require_login();

if so, just remove it and instead that get the user’s id from “fb_sig_profile_user” parameter.
example:

user = $_POST['fb_sig_profile_user'];

so, to avoid this above problem don’t do the followings…

  • do not use $facebook->require_login() for profile tab views
  • do not use external javascript libraries for profile tab views

ok, I believe we are done creating a simple profile tab. Now, let’s check whether it’s working or not. go to your profile page and click on the “+” sign under your name. If you don’t see the label of your application then search with the label you gave on your application settings.

you supposed to see the message “hi, your_name, glad to see your profile tab is working!:)

Reference:
http://forum.developers.facebook.com/viewtopic.php?id=23956

fbml rendering in iframe application

before proceeding the main topic, at first i want to describe how to develop iframe based facebook application. i assume that, the reader have minimum knowledge of how to develop canvas based facebook application. if you never develop any facebook application please visit: http://wiki.developers.facebook.com/index.php/creating_your_first_application

steps of developing iframe based facebook application:

1. when you setup a new application in facebook, choose “use iframe” for canvas page url.
2. now set the authentication code, at your bootstrap file:


<?php
include “facebook.php”;
$facebook = new facebook(’api_key’, ’secret_key’);
$user = $facebook->require_login();

//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(callback_url);
}
?>

3. and don’t forget to place the necessary facebook php library. http://wiki.developers.facebook.com/index.php/php

now i’m describing the main topic, that is how to render xfbml or fbml in your iframe based application.

1. first create a file called xd_receiver.htm
2. place xd_receiver.htm in the root directory. suppose your application base directory is: http://myapp.com/iframeapp . then place xd_receiver.htm in iframeapp folder. now add the following html code to xd_receiver.htm .


<!doctype html public “-//w3c//dtd xhtml 1.0 strict//en” “http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head>
<title>cross-domain receiver page</title>
</head>
<body>
<script src=”http://static.ak.facebook.com/js/api_lib/v0.4/xdcommreceiver.debug.js” type=”text/javascript”></script>
</body>
</html>

now in your view file, or may be layout file, place this code. here i’m showing the layout files format for iframe application.


<!doctype html public “-//w3c//dtd xhtml 1.0 strict//en” “http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xmlns:fb=”http://www.facebook.com/2008/fbml”>

<head>
<script src=”http://static.ak.facebook.com/js/api_lib/v0.4/featureloader.js.php” type=”text/javascript”></script>

</head>

<body>

<!– here is the fbml code in iframe application –>

<fb:serverfbml>
<script type=”text/fbml”>
<fb:fbml>

<fb:request-form action=”<url for post invite action, see wiki page for fb:request-form for   details>” method=”post” invite=”true” type=”xfbml” content=”this is a test invitation from xfbml test app <fb:req-choice url=’see wiki page for fb:req-choice for details’ label=’ignore the connect test app!’ />  ” >  <fb:multi-friend-selector showborder=”false” actiontext=”invite your friends to use connect.”>  </fb:request-form>
</fb:fbml>
</script>
</fb:serverfbml>

<!– here is the xfbml code –>


this is <fb:name uid=”<?=$this->userid?>” useyou=’false’> </fb:name>
my photo <fb:profile-pic uid=”<?=$this->userid?>” > </fb:profice-pic>

<!– remember all xfbml tags should be placed before below javascript code –>

<script type=”text/javascript”>
fb_requirefeatures(["xfbml"], function(){
fb.facebook.init(”place here the api key of your application“, “xd_receiver.htm”);
});
</script>

</body>

</html>

** remember xfbml is nothing but a subset of fbml that are supported for iframe application.

<fb:serverfbml> : this tag is used to renders the fbml on a facebook server inside an iframe. details of this tag is here: http://wiki.developers.facebook.com/index.php/fb:serverfbml

references:

1. http://wiki.developers.facebook.com/index.php/xfbml
2. http://wiki.developers.facebook.com/index.php/cross-domain_communication_channel
3. http://wiki.developers.facebook.com/index.php/php
4. http://wiki.developers.facebook.com/index.php/creating_your_first_application

how to successfully update all of your user’s profile offline, at once! – part 1

sounds crazy right? but actually you can make a great use of this feature in your facebook application. lets think that your application is kind of a todo-list or birthday reminder. now your users will create tasks or added friend to be notified when their birthdays arrive, or when the eta of a task is in 24 hours. in these cases you may have to update those user’s profile in background so that when they visit their profile page – they will see the latest information, and that will be very useful for them.

there are two ways to accomplish this task

1. by calling setFBML offline, using any of user’s session key.
2. by using <fb:ref /> with an url handler, which is a smart way indeed.

in this article i am going to focus on first technique. next article will focus on 2nd one.

updating using profile_setFBML()
to use this api offline, you first need a session key. the following code will print the session key for you.


<?php
echo $facebook->api_client->session_key;
?>

this code will output something like “6de106fa7e2de0820b091f12-503274632” which is my session key for this application.

now you can update all of your user’s profile using the following code. please note that i have used batch api for the sake of performance.


<?php
require_once 'client/facebook.php';

$appapikey = 'ff0b3d87fc42915533e15dc238f2d447';
$appsecret = 'app_secret_key';
$sessionkey = "6de106fa7e2de0820b091f12-503274632";
$facebook = new Facebook($appapikey, $appsecret);

$uid1 = 657561905;
$uid2 = 503274632;

$facebook->api_client->user = $uid2;
$facebook->api_client->session_key = $sessionkey;

$facebook->api_client->begin_batch();

$facebook->api_client->profile_setFBML(NULL, $uid1, "Offline profile <fb:name uid='{$uid1}' useyou='false' />", NULL, 'mobile_profile', 'profile_main');
$facebook->api_client->profile_setFBML(NULL, $uid2, "Offline profile <fb:name uid='{$uid2}' useyou='false' />", NULL, 'mobile_profile', 'profile_main');

$facebook->api_client->end_batch();
?>

if you need to update thousands of your user’s profile at a time, using the batch api is a must or you will suffer from timeout. now you can execute this script by either command line “php <script_file>.php” or by accessing it via browser :)

pretty neat, eh?

stay tuned for next part of this article where we will tell you how to update profile data offline using <fb:ref /> with an url handler :)

publishing on your friend’s mini feed (no session key)

the way superpokey or other applications do this, first they ask you to select some friends from your friends list, then they ask you to publish on their wall. at this stage a popup dialog opens up and asks if you really want to publish that story on your friend’s wall. if you agree, the news goes straight to your friend’s wall.

so how do they do it? you know the publishActionOfUser() actually publish feed’s on your wall, but there’s no guaranty if the news will go to your friend’s news section. so to do this, you have to use feedStoryForm. this form was introduced in facebook old profile, but comes in a new flavor when the profile section is completely redesigned by facebook. feedForms are used to publish news on user’s mini feed as well as his/her friend’s wall. but it always asks the user to authorize the publishing of news first. lets see how it actually works

step 1: register feed template
first, you have to register a feed bundle for your application. later we will use that feed bundle for publishing stories. so lets open feed console and select your application. feed console is accessible at http://developers.facebook.com/tools.php?feed

picture-4

now click on next. in the next screen you have to input a one line feed template. to check if you template is valid, you can also input sample data to pass to this template as “template data” which is infact a valid json object. lets do this

one line feed story

note one thing that to share a feed with friends, you must put {*target*} token in the one line feed templates.

our one line feed template is: {*actor*} is publishing some news about {*subject*} on friends wall and he wants to share it with {*target*}
parameters are: {”subject”:”fishing”}

now click on next to create short story template.
short story template

short story title template: {*actor*} is sharing some news about {*subject*} with {*target*}
short story body template: {*content*}

params: {”subject”:”fishing”, “content”:”The fishing goes superb in this sunny weather”}

now click on the “Update Preview” to check the validity of our short story feed. If it’s valid, lets proceed to next step of “Full Story Template” by clicking next. both short story and full story feeds are optional. this time we will skip full story template. so on the next screen just click “skip” and proceed to final screen.

now we are on the final screen of “Creating Action Link”. lets understand what is action link. check the following picture for details of our parameters and how it will appear on your friends wall.

action link

ok, we are done – now click on next and on the following screen click on “Register Template Bundle”, a popup dialog box will confirm you that the feed has been created and it will also show you the id of this feedbundle. note that id.

feed bundle id

step 2: include the feedStoryForm in your application
as we have our feed bundle registered, now it’s time to go into action. lets include the feed form in our application. here’s the code


<?php

require_once 'config.php';

// Greet the currently logged-in user!
echo "<p>Hello, <fb:name uid=\"{$uid}\" useyou=\"false\" />, Its story time</p>";
?>
<form method="post"
          fbtype='multiFeedStory'
          action='http://sandbox.ofhas.in/fbtest/feedstory.php'>   

	<b>What's it all about?</b><br/>
           <input size="50" type="text" name="subject" id="subject" value="" /><br/>
           <b>Ok! tell your friends more about this</b><br/>
	<textarea cols="50" rows="8"  name="content" id="content" ></textarea><br/>
	<b>Thats cool, so whom do you want to inform about it?</b>
	<div style="margin:10px 0 10px 0">
		<fb:multi-friend-selector condensed="true" />
	</div>
	<input type="submit" value="Publish News" label="Publish News" >

</form>
<script>
function shareDone()
{
     new Dialog().showMessage("Info","Successfully shared your news with your friends");
}
</script>

output will be something like this

output

the config.php just initiated the facebook object, so nothing to mention about that. but now we have to code the handler of the feed story request that facebook will make when your users will hit the “Publish News” button.

step 3: feed story handler
this file will be invoked internally by facebook over http. in this file you have to process the parameters of yoru feed form and return a valid response to facebook as a json object so that facebook can proceed further to publish your user’s news. lets see how it works – here’s the code


<?php
$subject = $_REQUEST['subject'];
$content = $_REQUEST['content'];
$actionsubject= $subject;
?>
{"content": {"next_fbjs":"shareDone();",
                   "feed": {"template_id":48644843809,
                                "template_data": {"subject":"<?=$subject;?>",
                                                            "content":"<?=$content;?>",
                                                            "actionsubject":"<?=$actionsubject;?>"} } },
 "method":"multiFeedStory" }

So we are done!

now when user’s will click on “Publish News” button after selleting friends, he will see a dialog box pops up for the authorization to publish the news – like this

picture-15

user can select whether he wants to publish “short” or “one” line feed story. remember we had skipped the full story template? if we created full story template, user will get another option like “full” in this dialog box. so when this dialog box pops up, user will have to click “Publish” to publish the story.

check out the published feed on your friend’s wall
picture-16

let us know your comment if you like our article. we are coming with new recipe soon.

hello fb cookbook reader

hello everyone, we have just launched!

our plan is to make it one stop solution for all your facebook application development needs. you will get answers to all your questions. we will mainly focus on development of applications for facebook, and sometime we will also review interesting applications and their cool features which you might have stumbled upon.

stay with us, we will try to answer all of your questions in this cookbook.


<?php
echo "hello readers of  fbcookbook";
?>