Friday, January 2, 2009

Facebook Application Part 2 : Scripting your App

(If you missed the Part-1 click here)
Now time to get hands on php. What I will do here is show you how to get access to the different parts of facebook API and also indicate my experiences. I would just indicate how to get the integration going and won’t dwell into what the app will do. You are a better judge to identify what the app can and should do. I am for this tutorial just show you how to load a flash file and also show you how to communicate with this flash file using php and XML. I will not be providing you with any sample files. Its left to your imagination and engineering what you want to make out of the app.

You will need to add the official Facebook PHP Client Library package into the webserver which is included in the package found here.

I will divide my app into these files:

  • Index.php: will be the main producer of the app. It will load the flash file and render the fbml part of the page. You will need to include facebook.php from the client library in the include.php
  • Invite.php: This is an optional page which includes some description how to get access of different friends
  • config.php: This will include all the application related stuff. It will be used to
  • db.php: Will hold all the library functions related to connection to the database, queries, and other support functions
  • xml.php: This is to read and write as xml format – intercommunication between flash and php.
The architecture of the app is a simple one:
Lets deal with the index.php for the starters. It would need to have the initial debugging information.

config.php
Then in the config file would contain the api_key and secret information regarding the facebook in this way.
$appapikey = 'gdhsgdhgsdjgsgadkshgdjgsadjgsadhg';
$appsecret  = 'dhfdsvfbvdsfnvdsnbfvbsdvfhdskhfiu';
Also include the details regarding the database as follows
$host = "localhost:3306"; //hostname is usually localhost by default
$db_user = "root"; //insert the name of the user here
$pass = "y6ju808";  //insert the password here
$database = "DATABASE_NAME";  //insert name of database
$table = "TABLE_NAME";  //insert
Some information regarding the invite page:
$app_name = "APP_NAME";
$app_url = "";
$app_image = "";
$invite_href = "invite.php"; //invite page
index.php
By adding the following in the index.php

error_reporting(E_ALL); // in the beginning to be able to debug errors in the file.
Also you will need to include another text file by name .htaccess, its contents are just a line:

php_flag display_errors on //to enable the debug flag
Next thing required is to include the config file and the facebook.php (from the client library)
require_once('config.php');
require_once(‘facebook.php’);
You need to add the following stuff to get a facebook object and to specify a user login
$facebook = new Facebook($appapikey, $appsecret);
$user = $facebook->require_login();  //Makes the user login to facebook
At this point of time, it’s ready for testing... You could try to login to your app through facebook by calling it in the browser – the link
You will just be asked to login if you haven’t to facebook due to the last line that requires to login in the index.php.

Next, it’s time to include the flash file. You would require having it as a swf format to be included. You would be using the tag from the facebook API.
Use it as follows:

          >fb:swf
            swfsrc='/flash.swf'
            Align='center'
            scale='showall'
            Width='100' Height='100'
quality = 'high' >
Here we are now…. We must have the flash file now when you launch the link in the browser.
FQL is a way to query the Facebook data you can access through the other API functions, but with a SQL-style interface. In fact, many of the normal API calls are simple wrappers for FQL queries. Some examples of how to run some queries to the fb database through fql are as follows. Please refer to the original documentation of fql for more examples and detailed references here.

This is a function to return an associative array of friends of UID who are using the APP:
function get_fb_friends($facebook, $user) {
      $result_friends = $facebook->api_client->fql_query('SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = '.$user.') AND is_app_user = 1');
$l_Friends_app_user = array();
foreach($result_friends  as $f_list){
            $l_Friends_app_user[] = $f_list['uid'];
}
      return $l_Friends_app_user;
}
invite.php
Next step is to include an invite page in the application. You could get the contents and documentation for the invite page from here.

db.php
I am providing some explanations to helper functions to connect to the database in this file. It provides some basic database related functions. I am providing a very generic list of functions and will help you in setting up your custom application and database based on these.
You can use phpMyAdmin to create the database and manage them. The user interface of this DB Admin tool is quite friendly and also provides a mechanism to import or export complete databases.

When talking about a database, the following are some of the common list of functions that you one would most commonly require. The config.php file would have the information required by these functions specified. So, make sure config.php is evaluated before calling any of the following helper functions.

  • Connection to the database: A connection has to be made to the database before executing any query to the databse.
function get_db_conn() {
$conn = @mysql_connect($GLOBALS['host'], $GLOBALS['db_user'],
 $GLOBALS['pass']) or
      die("Could not connect: " . mysql_error());
     
  mysql_select_db($GLOBALS['database'], $conn);
  return $conn; 
}
  • Query to add a list of records: Here, I have created a Table called USERS in my database using phpMyAdmin. I will get store the facebook user id of all the users who visit my app in facebook. You could optionally include other information regarding the user collected from the fb database or any other custom created information liked to your app. This function need to be passed the UID (stored in the $user created earlier) as an argument.
function add_user($user){          
      $l_query = "INSERT INTO USERS SET USER_ID = '$user'; 
      $l_add_user = mysql_query($l_query, $conn) or
            die("could not add the user..");
           
      $l_query = "FLUSH PRIVILEGES";
     mysql_query($l_query) or 
die('Error, insert query failed');           
      return $l_add_user;
}
  • Query to get a list of records: This is an example of a query being made to the MySql database to get a list of records from the database after a connection is made. This particular query would get all the details regarding the current user from the database.
function get_user_data($user){
 $query = "SELECT * FROM USERS WHERE USER_ID='$user'";
       $res = mysql_query($query, $conn);
       
       $l_query = "FLUSH PRIVILEGES";
       mysql_query($l_query) or 
die('Error, insert query failed');     
return $res;
}
You can call the function from anywhere by passing the current facebook user id (UID in $user that we have created above).

xml.php
There comes a need to get transfer data across from php to flash. XML would prove to be the best way for this purpose.  This is an example of the php script to print out the xml data which can be accessed from flash and used appropriately in flash. There are many methods to write xml data in php, I have chosen the dom object model method to accomplish this. It’s an efficient and an easy way to write xml data without any syntax errors. More about this can be found here.

In the following example, I am printing the UID under the USER -UID tag.
//Creates XML string and XML document using the DOM
 $dom = new DomDocument('1.0');
//add tag
$t_user = $t_person->appendChild($dom->createElement('USER'));
 //add tag under the tag
 $UID = $t_user->appendChild($dom->createElement('UID'));
 //add text node element to tag
 $UID->appendChild($dom->createTextNode($user));
$dom->formatOutput = true; // set the formatOutput to true
 // save XML as string or file
 $test = $dom->saveXML(); // put string in test
 print($test1);
Depending on the needs, you could print the specific information of your app. The page will print out the XML information when run which can be grabbed and used in flash. For more information regarding the usage of XML in flash can be found here.

Also there might be instances where you might have to read the information sent from flash as xml as text/xml. This data that is posted from flash to this php file can be read by listening to it using these following commands:
// Make sure the user is posting
    if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
    {
        // Read the input from stdin
        $postText = trim(file_get_contents('php://input'));
    }
$postText = $GLOBALS['HTTP_RAW_POST_DATA'];

Now you could access the data in this xml string using the built-in function simplexml as follows:
$xmlobj = simplexml_load_string($postText);
print header("Content-type: text/plain");
//Say the XML DATA has the USER ID in it..
$l_user = $xmlobj->UID;
Now you get hold of the UID which has been passed from the flash…..

I have come to the end of this tutorial. My sole intention of this tutorial is to fill some gaps generally present in the many of the tutorials available on the net.. Good luck with your ventures.. Have fun..