Learning Facebook Platform Fundamentals !! Complete information on it

Learning Facebook Platform Fundamentals

As mentioned in Chapter 1, there are five main components of the Facebook platform: API calls, Facebook Markup Language (FBML), Facebook Query Language (FQL), Facebook JavaScript (FBJS), and the client libraries. I consider the client libraries for the various languages to be part of the platform because they are useful abstractions for the specific language in which you are implementing your code. The examples in this chapter will utilize the PHP client library from Facebook, so if you’re using a different client library, your syntax will be slightly different. It’s important to remember that this chapter is not meant to be an exhaustive reference for the platform (Facebook has a wiki for that at http://wiki.developers.facebook.com), but it will cover the major elements you will likely encounter when developing applications. Client Library Primer The official client libraries written by Facebook are of the PHP and Java variety. Other language libraries are listed on the Facebook developers web site, but in the interest of simplicity, I’ll cover only the PHP library (specifically the PHP 5 library). If you’re working with other languages, most of the concepts should be the same, but depending on how the developer who wrote the library chose to implement certain elements (and the characteristics of the language the libraries are being implemented in), the way methods are called and named might be slightly different. As a word of warning, some libraries are better documented than others; some have web sites replete with example code, and others have just a link for a download. If you run into a problem and you can’t get help with your language-specific version, take a look at the documentation for the “official” client libraries for PHP or Java. Facebook’s PHP client library consists of two main object classes, Facebook (in facebook.php) and FacebookRestClient (in facebookapi_php5_restlib.php). As you might expect, the FacebookRestClient class abstracts interactions with Facebook’s API. The Facebook class utilizes the FacebookRestClient class’s methods to further abstract common interactions with the Facebook platform. For instance, instead of writing a procedure to 32 Learning Facebook Platform Fundamentals require a user to have a session key to work with your application, the Facebook object has a method named require_login() that checks for the session key and, if it doesn’t find one, redirects the user to Facebook to perform the authentication and then returns the user to your application. You use the classes just like any other PHP class with require_once (or your other favorite way to create objects): /facebook.php'); /** * Set your API and secret keys */ $api_key = ''; $secret_key = ''; /** * Initialize a new instance of the Facebook client object */ $facebook = new Facebook($api_key, $secret_key); ?> Your API and secret keys are assigned to you in your My Applications portion of Facebook’s Developer application (http://www.facebook.com/developers/apps.php). Once instantiated, the Facebook client libraries make it easy to interact with the Facebook platform. If you actually look at the code in the library, you’ll notice that it contains a few different classes. For instance, when you create a Facebook object, that class is including a library to make the REST calls (facebookapi_php5_restlib.php). If you are using PHP to write a desktop application, the main change is that you would use the facebook_desktop.php file, which extends the Facebook object but is better suited to desktop applications. The facebookapi_php5_restlib.php file is the real workhorse for your application and is where you will find most of the functions you will use in your application. One nice aspect is that the developers of the Facebook platform used phpDoc conventions, so generating complete documentation for the platform is relatively simple. If you don’t have a version of PhpDocumentor, you can download it from SourceForge at http://sourceforge.net/projects/phpdocu/ or use PEAR to install it: Learning Facebook Platform Fundamentals 33 pear install PhpDocumentor PEAR should install a new script that you can call from the command-line script, which you then can call to create the documentation: phpdoc -t /path/to/output -d /path/to/facebook_client_library -pp on –ti Facebook Client Documentation This line will set the output directory (-t), take a look at the client library path (-d), parse private functions within the code (-pp), set an HTML title of “Facebook Client Documentation” (-ti), and then output the results in HTML using frames. There are many more options for producing documentation, but these options will produce very useful documentation while you develop your Facebook application. For more information about using this tool, check out the phpDocumentor web site at http://www.phpdoc.org/. API Primer Facebook has some rather convenient out-of-the box tools for interacting with its back end. At the core of the platform is a set of API calls that wrap more complex code into a single call. In fact, most of the API calls are simply wrappers for complex FQL calls. So, without further adieu, let’s take a look at what you have available to you through the API calls. Facebook’s API methods are broken into logical groups of calls. These API calls are also where your first interaction with the platform comes into play. You don’t need to use the client library—it just makes things faster since you would need to write these in your language in order to interact with the platform. To set up the client library for PHP, you simply include the client library in your code. For example, the following snippet makes sure users are logged on to Facebook before displaying a list of the user’s friends. Figure 3-1 shows the results. '; $facebook_config['secret_key'] = ''; /** * include the Facebook client library */ require_once('/facebook.php'); /** 34 Learning Facebook Platform Fundamentals * Set up the facebook object */ $facebook = new Facebook($facebook_config['api_key'], $facebook_config['secret']); /** * Ensure the user has logged on to Facebook */ $user = $facebook->require_login(); /** * Make an API call to call get a user's friends using the PHP library's * library */ $friends = $facebook->api_client->friends_get(); echo "
Friends:" . print_r($friends, true). "
"; ?> Figure 3-1. Results of friends_get API call You’ll notice a few things in this example. First, you’re just throwing the results from the friends object on the screen. I’ll cover interacting with the resulting code with FBML a bit later. Second, the syntax for interacting with the API is abstracted into methods in the Learning Facebook Platform Fundamentals 35 Facebook object. You first set up the Facebook object with the API and secret keys that Facebook assigns to you when you set up your application. You’ll also notice that you require the user to be logged on to Facebook in order to execute the code. This example uses the require_login() method and stores the user’s identification number (UID) in the variable user. The next call actually queries the Facebook API method friends.get by wrapping it in the PHP method friends_get. Since the facebook object holds the user’s identification number (their primary key or UID), there’s no need to pass the UID to the API request. From this short sample code, you can see that the PHP code is actually setting up a REST client to call the facebook.friends.get API method and returns an array of user identifiers: /** * Returns the friends of the current session user. * @return array of friends */ public function friends_get() { if (isset($this->friends_list)) { return $this->friends_list; } return $this->call_method('facebook.friends.get', array()); } The client libraries allow you to concentrate on developing your application rather than recoding your interactions with the platform. Since you need to know what you can do with the API, let’s take a slightly closer look at the rest of the calls and what they do. Authentication The REST API has two methods for dealing with authenticating your users. The method facebook.auth.createToken creates an authentication token (auth_token) that is then passed to the Facebook authentication mechanism. After the user is logged in, the second REST method, facebook.auth.getSession, will contain this token in the response, but only if you specifically request the auth_token in the response. Authentication is usually (at least when it’s done well) a big headache for developing online applications. Because Facebook takes responsibility for these actions, you don’t have to purchase SSL certifications, implement your own encryption schema for passwords, or even worry about sessions. In the case of the PHP client library, you start the authentication procedure by calling the Facebook object’s require_login method. By calling this method, your users are redirected to Facebook’s login pages (https://login.facebook.com/login.php), which are passed your API key, and the user is given a session key and redirected to your callback page. The only difference is that when 36 Learning Facebook Platform Fundamentals the user enters the application for the first time, they are asked to accept the terms of service for the application. Now, you might find yourself in need of performing some task (such as updating FBML), but instead of logging into Facebook every time, you want to update the data to use some sort of scheduled task. You are able to do this with an infinite session key. The process to get your infinite key is a bit convoluted (but, hey, you have to do it only once for each application). After creating your application, create a new page (infinite_key.php) in your callback domain that creates a new Facebook object and echoes your session_key: '; $facebook_config['secret_key'] = ''; require_once('/facebook.php'); $facebook = new Facebook($facebook_config['api_key

'], $facebook_config['secret']); // force a login page $user = $facebook->require_login(); $infinate_key = $facebook->api_client->session_key; echo($infinate_key); ?> Once you have this code on your server, log out of Facebook, clear your Facebook cookies and browser cache (just to make sure nothing funky is going on), and then go to the page you just created on your server (that is, not the application URL, but the actual URL). You will be asked to log on again, so do so, but make sure you check the No Longer Have to Log In to Facebook box. After you’ve logged on, you should see the infinite key that you can then use in your code. You can now use your own UID and key in other code to perform anything that needs to happen on a regular basis with the set_user function in the facebook object: Learning Facebook Platform Fundamentals 37 '; $key = ''; $facebook->set_user($uid, $key); // code that needs to be executed ?> The infinite key is a powerful construct for your Facebook application that you might find you need to implement. Most of the folks who have needed this are updating FBML for features such as mini-feeds or pushing content to their user’s profile page. Events Event calls have two main wrappers to retrieve information on events. The first, facebook.events.get, returns a response based on the filters passed to it. The second, facebook.events.getMembers, returns the RSVP status for Facebook members for a given event. FBML To deal with some of the more advanced features of FBML, Facebook has three API methods to help you. The facebook.fbml.refreshImgSrc method fetches and caches an image at a given URL. To refresh content from a given URL, you use the facebook.fbml.refreshRefUrl method. Lastly, to use content as a handle in FBML, you can call the facebook.fbml.setRefHandles method. Feed To update a user’s news feed, the REST API has two methods. To publish information to an individual user’s feed, the facebook.feed.publishStoryToUser method will publish information to a user’s feed based on their session key (session_key) and their user ID (uid). You add the title, body, and various links, depending on what you want to publish. The second method, facebook.feed.publishActionOfUser, publishes a mini-feed story to the user’s account, also based on their session key and user ID. 38 Learning Facebook Platform Fundamentals FQL As I’ve mentioned, most of the calls in the REST API are wrappers for complex, but common, FQL queries. The facebook.fql method takes a query and returns a response object based on your syntax. In the Facebook documentation, most of the API requests have their FQL equivalents, so if you see you need something slightly different from what is provided in the API calls, check out the FQL equivalents before you start writing from scratch. Friends When you’re developing applications, you might find it necessary to look at the friends of your users. There are three methods provided to deal with this. The method facebook.friends.areFriends will tell you whether two people are friends. The facebook.friends.get method returns a structure of the user’s friends’ user IDs. Lastly, the facebook.friends.getAppUsers method returns a structure of the friends of the user who have installed the application on which you’re working. Groups If you want to work with your user’s groups, the REST API has two methods that return information about their visible groups. When you call the facebook.groups.get method, you can retrieve all the groups the user belongs to, or a subset of these groups, by using the method’s filtering mechanism. The second method, facebook.groups.getMembers, returns the user IDs (UIDs) for a given public group. Marketplace Facebook’s marketplace is a place to buy/sell items, list jobs, list housing, or even request items to purchase/borrow through Facebook. You’re able to search the Facebook marketplace with facebook.marketplace.search. There are getters and setters for listings with facebook.marketplace.getListings and facebook.marketplace.createListing. You can also remove listings with facebook.marketplace.removeListing. Facebook also has a category and a subcategory getter method, facebook.marketplace.getCategories and facebook.marketplace.getSubCategories. Learning Facebook Platform Fundamentals 39 Notifications Facebook allows you to send and receive notifications in your application with the REST API. You can expose your user’s request notifications, by using the facebook.notifications.get method, to see outstanding notification responses. You can also send notifications to your users with the facebook.notifications.send method and send invitations with the facebook.notifications.sendRequest method. Photos With more than 60 million images added each week by Facebook users, there are several REST methods to interact with users’ images. You can tag images with the facebook.photos.addTag method or create photo albums with the facebook.photos.createAlbum method. You can get a user’s individual photos with the facebook.photos.get method or a listing of their albums with the facebook.photos.getAlbums method. You can also get the listing of the tags that individual photos have with the facebook.photo.getTags method. I’ll c 40 Learning Facebook Platform Fundamentals to provide a specific parameter for an API call). The error codes are returned with both a numeric value and a message. Generally, if you receive an error message (in a structure), it’s rather obvious when you read the error message (in the err_msg element). If you can’t figure out what’s going on with a specific call, it’s always a good idea to check out the code in the API Test Console (http://developer.facebook.com/tools.php). Although this won’t give you any more information than you are getting returned, it can help you narrow down what’s going on (in case you have multiple errors). Data Store API Facebook also has implemented an API for basic database manipulations with its Data Store API (which is still in beta as of this writing). This API provides a basic create, read, update, and delete (CRUD) API for storing data that you access through REST. If you’re unfamiliar with object-oriented database management systems (OODMSs), some of the terminology is a bit different from that for relational database management systems (RDBMSs). For instance, to use the Data Store API, you must define your schema (your database), which consists of object types (tables) and properties (columns). One of the really nice features of the Facebook Data Store API is that Facebook does not plan to charge for normal use! You basically have use of Facebook’s servers to perform your database manipulations for you. However, it’s probably not quite time to get rid of your RDBMS yet, because there aren’t any structured queries, full-text search, or transaction-level query processing in the Facebook Data Store API. Note ➡ The Data Store API is still in beta as of the writing of this book. Because of this, there is a chance that what I write here will change. Please consult the wiki documentation for the latest information before you deploy any projects using the Data Store API. The Data Store API consists of three basic functions: specialized tables, distributed tables, and associations that are split into five separate APIs (User Preference, Object Data Definition, Object Data Access, Association Data Definition, and Association Data Access). Since Facebook provides access to millions of users, the tables (objects) you create are distributed. Facebook does provide a specialized table of users that is optimized (if you find that you really need more, let the Facebook developers know at their Bugzilla site, http://bugs.developers.facebook.com/). The associations component of this API is a mechanism to provide performance for fast lookups (such as indexes). Because indexing tables in a distributed environment won’t necessarily provide a performance boost, this Learning Facebook Platform Fundamentals 41 mechanism has been implemented to provide fast lookups without centralized indexes or parallel queries. The user preferences for the API consist of 128-character strings, for which you can store up to 201 for each user (numbered 0–200). Access to the getters/setters are accessed through getters and setters in the REST API (facebook.data.setUserPreference and facebook.data.getUserPreferences). Data objects (that is, tables) are created with facebook.createObjectType. The object type takes a name and contains a set of object properties (that is, columns). Object properties have names and data types. You don’t quite have the same type of control over the data types with the API as you do with your own RDBMS because you are limited to integers, strings (less than 256 characters), and text blobs (with a maximum of 64KB). After defining your objects and object types, you create, read, update, and delete through the Object Data Access API. These are rather straightforward (facebook.data.createObject, and so on). To work with the associations between objects, you first need to define the relationship between objects in the facebook.defineAssociation call. You can define two types of associations: one-way, symmetric associations and asymmetric associations. If you’re familiar with RDBMS joins, think of an asymmetric association as a many-to-many join and a symmetric association as a one-to-many join. One-way associations are an association between objects that can happen only one way (in other words, there’s no need to look up a value by some ID) for a given object. You then create the actual associations with the Association Data Access API. These methods allow you to create, remove, and retrieve these associations and retrieve the object details from the data contained in the data definition. This can be confusing at first, so let’s look at an example: api_client->data_createObjectType("wallpost"); $uid = $facebook->api_client->data_defineObjectProperty("wallpost", "uid", 1); $time = $facebook->api_client->data_defineObjectProperty("wallpost", "timePosted", 2); $post = $facebook->api_client->data_defineObjectProperty("wallpost", "post", 3); ?> The previous snippet of code is analogous to the following SQL DDL: CREATE TABLE wallpost( 42 Learning Facebook Platform Fundamentals uid integer, timePosted timestamp, post text ) As you can see in this simple example, this can take a little bit to get used to because you’re not performing your typical SQL DDL; however, once you get your mind around how to create the objects, it’s relatively trivial to use the API as the persistence layer for your application. I suspect that this API will eventually make it out of beta and be quite a powerful tool in the Facebook developer’s toolbox, at least for those who choose to have Facebook manage their data. FQL Primer If you’ve worked with SQL before (and I assume you have), FQL isn’t a big deal. You use the same syntax as typical ANSI-SQL, and there are only nine tables to deal with. There are, however, some important differences. There are no joins, and FQL has not implemented the LIMIT, GROUP BY, or ORDER BY clauses that are common to ANSI SQL–compliant implementations. Before we go any further, let’s take a look at the tables and fields that are exposed to the Facebook Query Language. Tables Here’s a list to make sure you know what’s available to you in the different tables. (OK, these aren’t really tables; more likely these are views of specific data, but for simplicity’s sake, we’ll just call them tables.) • users(uid, first_name, last_name, name*, pic_small, pic_big, pic_square, pic, affiliations, profile_update_time, timezone, religion, birthday, sex, hometown_location, meeting_sex, meeting_for, relationship_status, significant_other_id, political, current_location, activities, interests, is_app_user, music, tv, movies, books, quotes, about_me, hs_info, education_history, work_history, notes_count, wall_count, status, has_added_app) • friend(uid1, uid2) • group(gid, name, nid, pic_small, pic_big, pic, description, group_type, group_subtype, recent_news, creator, update_time, office, website, venue) • group_member(uid, gid, positions) Learning Facebook Platform Fundamentals 43 • event(eid, name, tagline, nid, pic_small, pic_big, pic, host, description, event_type, event_subtype, start_time, end_time, creator, update_time, location, venue) • event_member(uid, eid, rsvp_status) • photo(pid, aid, owner, src_small, src_big, src, link, caption, created) • album(aid, cover_pid, owner, name, created, modified, description, location, size) • photo_tag(pid, subject, xcoord, ycoord) Functions and Operators Although the FQL language isn’t ANSI-SQL complete, it does have some simple operators and functions to help you work with user data. FQL has boolean operators (AND, OR, and NOT), comparison operators (=, >, >=, <, <=, <>), and arithmetic operators (+, -, *, and /). The functions included in FQL, although not exhaustive, allow you to perform some basic string manipulations. To conserve bandwidth, you can use the concat() function to group several tuples together: '; $facebook_config['secret_key'] = ''; require_once('/facebook.php'); $facebook = new Facebook($facebook_config['api_key'], $facebook_config['secret']); /** * Ensure the user has logged on to Facebook */ $user = $facebook->require_login(); /** * Construct the FQL request */ $fql = "SELECT concat(first_name, ' ', last_name) 3941d4f732e9db052c723207261284de 44 Learning Facebook Platform Fundamentals FROM user WHERE uid = '$user'"; /** * Pass the FQL to Facebook through the API client */ $fql_result = $facebook->api_client->fql_query($fql); /** * Print the results to the screen */ echo "
FQL Result:" . print_r($fql_result, true) . "
"; ?> The previous example simply selects the first and last names of the user who is currently making the request. The resulting page will display an array in the following format: FQL Result:Array ( [0] => Array ( [anon] => ) ) You might be saying to yourself, “This is pretty useless. What’s the difference between this and just calling both the fields?” Well, if you have any bandwidth concerns, you can alleviate some of those issues by using the concat function to put fields that you need together. For instance, you might want to put a specific string into your page that combines several fields in a specific way. Letting the Facebook servers do some of this processing before it gets back to your server will not only decrease your server load but can also cut down on your bandwidth in order to speed up your application. Not only can you do simple SQL-style selects, but you can also perform subqueries. Take, for example, this FQL equivalent for the facebook.events.get REST API call: SELECT eid, name, tagline, nid, pic, pic_big, pic_small, host, description, event_type, event_subtype, start_time, end_time, creator, update_time, location, venue FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid=uid AND rsvp_status=rsvp_status) AND eid IN (eids) AND Learning Facebook Platform Fundamentals 45 end_time >= start_time AND start_time < end_time I won’t go into the theory behind nested queries, but I will mention that they are very useful for testing set membership, set comparisons, and set cardinality. And, this expansion of the REST call serves as a good example for writing your own custom FQL expressions. You might find that you will need to take some additional processing to make sure your information is displayed in a specific order. You’ll have to do this with your client language. For PHP, you need to sort the array and then slice it. Let’s take the following: api_client->fql_query($fql); asort($fql_result); array_slice($fql_result, 0, 5); ?> The previous passes an FQL query to find events for the current user, sorts the resulting PHP array, and returns the array with the six elements (positions 0–5) of the query result. FQL allows you as a developer to have granular control of the information that you retrieve about your users from the Facebook servers. Although it’s not as robust as you might sometimes need (or want) it to be, you can generally get around FQL’s limitations with some post-processing in the language in which you’re developing. Additionally, as the complexity of your FQL increases with subqueries, you might at some point run into problems. As I’ve mentioned earlier, using the Facebook API Test Console at http://developer.facebook.com/tools.php is a great place to help debug your code. For instance, if you take the previous query and take out the WHERE clause so that your FQL statement reads as follows: SELECT eid, name, location FROM event WHERE eid IN ( SELECT eid
FROM event_member ) then, when executed, this will raise an error (shown in Figure 3-2) because you must have a limiting WHERE clause. Figure 3-2. XML error response If you missed it when you look at your code, the resulting XML response shows an error code of 601 and an error message of “Parser error: WHERE clause is required.” Fortunately, this is an easy fix, but you might find yourself working with more complicated interactions with FBML and FQL, and this tool can provide invaluable help in discerning where your bugs exist. Facebook Markup Language Primer The Facebook Markup Language (FBML) is the heart of the Facebook platform. You might see some folks referring to FBML as “fancy” HTML tags, but it actually does a little more than static HTML because it has a dynamic connection to the Facebook back end. If you have developed any web applications in ColdFusion or JSP (using JSTL), programming with FBML will be very familiar. The Facebook Markup Language is described on the wiki site as an “evolved subset of HTML,” so you have many of the same tags available to you as you do in normal HTML, but you also get a much richer tag set that allows you to code myriad interactions with the users very quickly. Valid HTML Tags For the most part, most commonly used HTML tags will work on the Facebook platform. If you’ve worked with HTML in the past, you’re already familiar with this part of the platform. One major difference between typical HTML and FBML is that “normal” Learning Facebook Platform Fundamentals 47 JavaScript is stripped from your code. For instance, you cannot use the onclick attribute in the anchor () tag to call JavaScript: click me
Although completely valid HTML and JavaScript, the previous will raise an error (shown in Figure 3-3) when your users look at the page containing this code. Figure 3-3. Facebook errors Don’t worry, if you need access to JavaScript for your application, Facebook has developed FBJS, which will allow you to use many of the conventions you typically see in JavaScript. When working with FBML, remember that it’s not exactly HTML, even though you use a lot of the same syntax. Your code has to be processed through the Facebook platform to ultimately generate the HTML that gets rendered to the user, so not everything you’re used to doing with HTML code will work. FBML Tags FBML-specific tags are really the meat of the Facebook platform. The tag set isn’t overly complex, but it has already gone through two iterations with FBML 1.0 and FBML 1.1. This change actually raises a sometimes-frustrating aspect in how Facebook changes the platform. When FBML 1.1 was announced in August 2007, developers basically had ten days to make their code compliant to the new specification. It is imperative that if you’re developing an application for Facebook that you keep up with the changes to the platform so your application doesn’t stop working. If you haven’t already subscribed, add the Facebook News feed (http://developers.facebook.com/news.php?blog=1) to keep abreast of changes. I’ll also take a moment here to talk briefly about some of the issues, err, enhancements that you will see when using FBML. One of the big things you’ll notice is that there are FBML tags that will act differently in different locations. As an example, you can use 48 Learning Facebook Platform Fundamentals iframes on canvas pages, but you cannot use the same iframe on the code in the profile box. There is also a queue of requested tags that are being considered for inclusion with the next FBML tag set iteration. Although not all of these tags will make it into the official language, it’s interesting to see what the developer community is requesting to be included. You can view and add to these requests at http://wiki.developers.facebook.com/index.php/Requested_FBML_Tags. The developer’s wiki for the Facebook platform groups the tags by their function. I believe this is perhaps the most useful way to work with the FBML because of the sheer volume of tags (almost 100 as of version 1.1). Also, because of this volume, some tags will necessarily have more information about them than others. If you find some of these descriptions and examples insufficient, please refer to the official documentation for the tags. FBML tags are set apart from other HTML tags with the fb prefix and follow the format . Conditionals FBML contains many conditional tests that can help you cut down on implementing this code in your application. At the heart of these conditionals is the tag: Hi
At first glance, this isn’t that useful because the value attribute will always be true. This is where your programming language comes into play. To actually make this do something useful, you need to be able to dynamically set this value. Let’s write a short test to see whether the logged-in user has a user ID of 12345 and show a customized message: require_login(); $test = false; // you may also use 1/0 for true/false if($user == 0000001){ $test = 1; } ?> This is the secret message.
Learning Facebook Platform Fundamentals 49 No secret message for you!
This is a nonsense example, but it shows how you can you use the / construct to display custom messages to your users. You will find that through your application development process you will start constructing more complex / statements. Fortunately, the developers of the Facebook platform anticipated this and have a set of tags that will do many of the most common types of conditional checking. As I stated earlier, Facebook tags act differently in different sections of the web pages. These conditional checks can occur only on the canvas page of your application: • displays content if a UID is in the specified network. • displays content if the logged-in user can view the specified content. This is often used to implement your own privacy features in your applications. • displays content if the user is logged on and has permissions to view the photo specified. • displays content if the specified user has accepted the terms of service for the application. • displays content if the user specified is friends with the logged-in user. • displays content if the user is a member of the specified group. • displays content if the viewer is the profile owner • displays content if the viewer is one of the specified users. • displays content if the specified user has added the application to their account. Unfortunately, there isn’t an FBML construct for else if logic. If you need to perform multiple conditional checks, you will need to properly nest your if statements. Alternatively, you can use the FBML’s switch construct. The FBML tag acts a bit differently than many programming languages that implement the construct. In FBML, the tag evaluates a set of FBML tags and returns the tag information from the first tag that returns something other than an empty string: 50 Learning Facebook Platform Fundamentals This is the default statement This code will display the contents of the tag since there’s no user with a UID of 0000001. You may at some point need something a bit more complex for your tests. You are able to nest and statements within an tag for these more advanced conditional analyses in your code: require_login(); $test = false; if($user == 0000001){ // Boolean true = 1 $test = 1; } ?> Inner default Outer Default As you’ve probably noticed, there’s no case statements with breaks that you normally see in other programming languages. If you’re familiar with the switch statements having case and break statements, just think of each tag as a distinct case with no need for a break statement. There are times where this could require more complex nesting of statements, but if you find your conditional statements getting too complicated, it’s probably a good idea to take a step back from what you’re doing and see whether you can find an alternative method to perform the same check. Also, as a programming note, the switch statement essentially has a break after the first true statement in the switch statement. If you place the tag at the top of your code block (which will always return true), the rest of your switch statement will not get evaluated. Learning Facebook Platform Fundamentals 51 User/Group Information Working with your user’s and group’s information is an important part of any Facebook application. You want to let your users easily interact with other users of your application, and there are some specific FBML tags to help with these interactions: • returns the user’s name for the uid passed to the tag. This function has a lot of customizable features to allow you to display the possessive of the user’s name and additional logic to handle users who have protected their profiles. For example, the tag returns “Anonymous” if the user has chosen not to show their name in their profile. • returns the name and a link of the group ID passed to the tag. • displays content to the specified user and no one else. • renders a pronoun for a specific user. This is a fun tag to use because it has several attributes that let you choose the different formats of the pronoun’s use, including possessive, reflexive, and objective forms. • renders a linked image of a user’s profile picture. By default this is a 50-by-50-pixel image. This is good for “iconifying” your user’s interactions. Profile Specific You might find that you need to provide different content depending on where your users are accessing the application from. Facebook provides the following tags for displaying content inside the user’s profile box: • displays content only when the profile box is the wide column. • displays the content only when the profile box is the narrow column. • builds a link on the user’s profile under their photo. You’ll use this in conjunction with setFBML to send information to the user’s profile. As a note, there is a 30-character limit for the contents of this tag. • renders a table of the users (specified by the tag) you have specified. This tag works only on a user’s profile page (will not render on the canvas page). • defines a user for use inside the tag. • defines a subtitle for the profile box. 52 Learning Facebook Platform Fundamentals Embedded Media Rich media is one of the cornerstones of the modern Internet…just look at YouTube. If you find a need to use embedded media in your application for music, games, or other rich media, you can use several tags to do this. This is an area in which FBML diverges from HTML because it is missing an tag. However, you are still able to use this functionality through the following tags: • inserts an iframe into your application to pull in external sources to your application. This tag cannot be used in the profile page. • renders a picture that is in the Facebook repository and the user has permission to view. • adds a Flash-based MP3 player that controls the MP3 file specified. Remember, this has to be the absolute path to the file. • renders a Flash object on the page of the specified absolute path. On profile pages, the SWF file is rendered as an image and rendered directly on canvas pages. • renders a Flash-based player to stream FLV content. This tag will use only .flv extensions, not other formats such as AVI. • is basically the same as the tag, but for Microsoft’s Silverlight-based content. Visibility on Profile You might encounter instances in which you want to display specific content to your users depending on their profile status with your application. FBML allows you to distinguish between the application owner, users, application users (those who have granted full access to your application), and those who have added the application to their accounts. • displays content if the user is the owner. As a side note, if the user isn’t the owner, this displays whitespace. • displays content to the specified user. • displays content if the user has granted full permissions to the application. • displays content if the user has added the application to their account. Learning Facebook Platform Fundamentals 53 Tools Tag-based languages such as ColdFusion and JSTL have many tags that build portions of your application for you. Similarly, FBML has a set of tags to help you build some very useful portions of your application: • generates code to add comments to an application. It takes care of posting and redrawing pages that are posted to for a given UID. • adds the JavaScript to your application so you can use Google Analytics to track your application usage. • displays content for mobile users (http://m.facebook.com). Content outside of these tags will be ignored for mobile users. • randomly rotates certain parts of your application content (for quotes, pictures, or even advertising). This tag not only can randomly choose an element from within the tag (defined by the tag) but also can weight these options to appear more often (or less often) than other options. Forms Working with form information is important in developing any online application. FBML has some constructs to help with these common tasks. • creates a form for sending requests. This is a great way to let your users send requests to add the application (when used with the tag). You cannot use this tag if you are using iframes. • creates a submit button for use with the tag. • renders a multifriend input field like the one used in the message composer. • renders an autocomplete input box of the user’s friends. • creates a JavaScript submit button for your forms. This is generally used when you want to use an image instead of a submit button, such as . 54 Learning Facebook Platform Fundamentals Other Here are some miscellaneous tags: • allows you to define a string to reference in FBJS. You can set this anywhere in your code, and it is not displayed to the user. For example: This is the rendered text. • allows you to define the specific version of FBML. Currently, the valid versions include 1.0 and 1.1. • displays the version of FBML that is currently being used. • redirects the browser to another URL in your application. • allows you to define FBML that resides at a specific URL that you then call through the tag. This is generally used when you want to update a lot of profiles without publishing the data on a per-user basis. • creates a share button with either URL information or specific metadata. • renders a time in the user’s time zone. • sets the page’s title tag. Editor Display To work with editing data, Facebook has derived a set of tags grouped in this section. The rendered form will display in two columns with the label on the left and an input field on the right. The one caveat to using the tags to create forms is that you cannot use mock Ajax. If you want to be able to use mock Ajax, you will need to manually create your own form. • is the outermost tag used to create an editable form. • creates a button for your form. • creates a container for one or more buttons. • creates a cancel button for the form. • allows you to insert whatever code you want, as long as it’s valid FBML. • creates two select boxes in the form for the month and day. Learning Facebook Platform Fundamentals 55 • adds a horizontal line divider to your form. • creates a select box populated with the months of the year. • creates an input box for your form. • creates a textarea box for your form. • creates select boxes for hours, minutes, and an a.m./p.m. indicator for your form. As an example of this usage, consider the following. Remember, the form the tag produces uses the Post method. If you use the tag, you will need to write some code on your server to then do something, but the purpose of this example was to show how to use these tags in conjunction with one another to create a form. In this case, the previous snippet will render as depicted in Figure 3-4. 56 Learning Facebook Platform Fundamentals Figure 3-4. Simple Facebook editor form Page Navigation Once you have your application completed, you’re going to want to develop a navigation scheme for your users. The main tag for this task is the tag that builds the familiar dashboard layout in Facebook. There are additional tags that you can lay out within the tag, including buttons, hyperlinks, and even help: • renders the standard Facebook dashboard for navigation. This is a container tag for , , and . Note that you cannot use the tag inside this tag. • is analogous to an anchor tag for the dashboard. • creates a link to the application’s help. This is rendered to the right side of the dashboard. • creates a button for in the dashboard. Learning Facebook Platform Fundamentals 57 • renders a title header. • renders a media header. This tag is generally used to display usercontributed content to specific users. • is a container to add tabbed-navigation style of links to your application. Individual tab items are added with the tag. You can see the difference between how the tag sets for the dashboard (Figure 3-5) and tabs (Figure 3-6) generate content. The tag allows you to nest , , and tags: Add Something Delete Something Help me Add Something Figure 3-5. Facebook dashboard using tags The tag, by contrast, allows only the tag to be nested: Figure 3-6. Facebook tabs using tag 58 Learning Facebook Platform Fundamentals Both of these tag sets provide different functionality to you. Typically you will use for creating an overall navigation schema, and you will use for performing functions within your application. Dialog Boxes As a note, this set of tags is still in beta mode, but basically this is a mechanism to provide modal dialog boxes for your application. This is really a fancy pop-up box to interact with your users. If this tag doesn’t fit your needs, you can also use FBJS to create this type of interaction between your users by utilizing the Dialog object. • is the container tag for the dialog box. • is an optional title for your dialog box. • is the message contained in the dialog box. • renders a button for the dialog box. Consider the following FBML snippet for constructing a dialog box: This is a test Content show fb:dialog The snippet will render a modal window as shown in Figure 3-7. Within the tag, you are also able to add other information (and other FBML) tags, such as forms to perform more advanced interactions with your users

Complete information on it

Figure 3-7. FBML <fb:dialog>
For example, take this snippet that generates a search form to search Facebook (or some
other site):
<fb:dialog id="fb_search" cancel_button="true">
 <fb:dialog-title>Search Facebook</fb:dialog-title>
 <form action="http://www.facebook.com/s.php" method="get">
 <input type="text" name="q" />
 <input type="submit" value="Search" />
<a href="" clicktoshowdialog="fb_search">Show Search</a>
Now, when the user clicks the Show Search link, a modal window will pop up, as
shown by Figure 3-8. When users hit the Search button, they are passed to the new server,
which in this case presents users with their search results.
60 Learning Facebook Platform Fundamentals
Figure 3-8. <fb:dialog> with form
As mentioned previously, you can make these dialog boxes using FBJS (using the
Dialog object). However, not everyone is a JavaScript expert, so the <fb:dialog> tags
provide a convenient method to do most of the same things you can do with FBJS without
writing any FBJS.
You might want to add the ability for your users to do something along the lines of your
wall. There is functionality for this with the following:
• <fb:wall> renders a wall-like section in your application that has <fb:wallpost>
elements from your application users.
• <fb:wallpost> is the message for the wall post that can contain an <fb:wallpostaction> element.
• <fb:wallpost-action> adds a link at the bottom of the wall post content. Even if you
put it at the beginning of the <fb:wallpost> element, the display will still render at the
bottom of that particular post.
Walls are pretty easy to implement, assuming you have some type of persistence
mechanism (such as an RDBMS). Assuming you do have an RDBMS, you would simply
make a new table with three tuples (columns) to hold the UID (bigint), the actual post (text),
and a time stamp (for indexing). Additionally, you could add a primary key field, though
the time stamp should suffice for this. Now, all you need to do is loop over these results to
provide them in the <fb:wallpost> tags, and all this should be wrapped in <fb:wall>. The
only hard part is deciding how many posts you want to display on a page.
Learning Facebook Platform Fundamentals 61
Mock Ajax
If you’ve been working with online applications over the past several years, chances are
you’ve at least heard of Ajax (asynchronous JavaScript and XML). This technology allows
you to work with dynamic information from within a single page without needing to repost
the data. The basic idea of how Facebook has implemented this is that you make a call to
your callback URL (the code hosted on your server) and echo it back to the user.
You’ll need to create a proxy file on your server to handle the responses from your
mock Ajax. For our sample purposes, I’ll show how to create a bit of code that allows users
to type in text, and the Facebook platform will echo back the SHA1 hash of the string using
mock Ajax. First, you need to create the Ajax proxy:
* @title hashproxy.php
 echo("Your encrypted text: " . sha1($_POST['q']));
This file doesn’t do anything really interesting; it just echoes back the string it’s passed
as an SHA1 hash. There’s no special processing, but if you were using this to produce
search results from, say, a database, you would process your results here.
Next, you need to add some FBML to a page to call the proxy. The FBML code to do
this is pretty straightforward because it is similar to an HTML form. The only real
difference is in the submit button that includes three additional FBML-specific attributes:
<form id="hashForm">
 <label for="clearText">Text to hash:</label>
 <input type="text" name="clearText" />
 <input type="submit"
 value="Hash it"
 clickrewriteurl="<your_callback_domain>/hashproxy.php" />
<div id="hashResult"></div>
This bit of code will create a form on your application’s page. When a user enters text
into the input box and clicks the submit button, Facebook will take the results of the form
62 Learning Facebook Platform Fundamentals
(defined by the clickrewriteform attribute) and write the results from the hashproxy.php file
(defined by the clickrewriteurl attribute) to the hashResult div (defined by the
clickrewriteid attribute).
You can also include a loading indicator to help you let your users know that something
is being processed. You just need to add a clicktoshow attribute that maps to a new element
in the hashResult div:
<form id="hashForm">
 <label for="clearText">Text to hash:</label>
 <input type="text" name="clearText" />
 <input type="submit"
 value="Hash it"
 clicktoshow="thumper" />
<div id="hashResult">
 <img src="<your_callback_domain>/loader.gif" id="thumper"
Note ➡ Need a loader? There are several really nice sites where you can grab these. One site that I like is
Ajaxload (http://www.ajaxload.info), which allows you to set the foreground and background colors for
a set of animated GIFs. Another nice site with a collection of loaders is at http://www.napyfab.com/ajaxindicators/. Just remember that using these indicators does add a little bit of overhead to your application
because it has to start and stop the indicator when it gets its information. Depending on what you’re doing,
you might spend more time turning the image on and off than actually displaying the text, so doing a little
testing to see whether having these load indicators helps with the design can go a long way in alleviating
frustrations for your users.
You can also use mock Ajax from within anchor tags (<a>) with one small difference.
You need some type of form to work with the mock Ajax, so you’ll need to create an empty
<form id="dummyform"></form>
<a clickrewriteform="dummyform"
Learning Facebook Platform Fundamentals 63
 clicktoshow="thumper">click me</a>
<div id="clickResults"></div>
This type of interaction is very useful, and it will be able to handle most of the basic
types of information retrieval you might need in your application. However, you might find
that simply echoing results to the page falls a bit short of your needs. To develop more
robust Facebook features that leverage JavaScript-style code, Facebook has developed the
Facebook JavaScript language, which I’ll cover next.
Facebook JavaScript Primer
As I stated earlier, Facebook will strip most JavaScript from your code because of security
concerns. However, the Facebook developers realized that JavaScript is useful for
developing enriched user interfaces. As a result, Facebook created its own version of
JavaScript called Facebook JavaScript. However, I should note that FBJS is still currently
in beta and subject to change.
If you’ve developed for other social web sites that allow you to use JavaScript, you
know that they force you to use iframes in order to isolate their code. Facebook, however,
takes a different tact for dealing with JavaScript. It takes its FBJS, parses the code, and
prepends functions and variable names with your application identifier. For example, the
function say_hello(name){
 var my_string = 'this is a sample.';
 return my_string + ' ' + name;
is translated into this:
function <app_id>_say_hello(<app_id>_name){
 var <app_id>_my_string = 'this is a sample.';
 return <app_id>_my_string + <app_id>_name;
There are a few things to keep in mind when you are using FBJS in your applications.
For instance, depending on the area your application resides in, your scripts will perform
differently. Let’s look at the following example from the Facebook wiki:
64 Learning Facebook Platform Fundamentals
<a href="#" id="hello" onclick="hello_world(this); return false;">Hello World!</a>
function random_int(lo, hi) {
 return Math.floor((Math.random() * (hi - lo)) + lo);
function hello_world(obj) {
 var r = random_int(0, 255);
 var b = random_int(0, 255);
 var g = random_int(0, 255);
 var color = r+', '+g+', '+b;
 obj.setStyle('color', 'rgb('+color+')');
This simple program randomly sets the color of the anchor text “Hello
World”…nothing too special there. However, depending on where your application is
located, it will behave differently. In the profile box, inline scripts like the previous are
deferred until the first “active” event is triggered (for example, anything that requires a
mouse click).
Note ➡ In early versions of FBJS, it was necessary to encapsulate the script code in HTML comments within
the <script> tag. Facebook has since updated the code parsers to make this step unnecessary. And, as the
platform becomes more sophisticated, other subtle changes like this should be expected.
DOM Objects
Part of Facebook’s implementation of FBJS includes DOM objects. If you’ve worked with
DOM before, FBJS typically prefixes the JavaScript equivalent with get and set. For
instance, the JavaScript href object is called with getHref() and is set with setHref().
Learning Facebook Platform Fundamentals 65
Putting It Together
Now that you have an idea of how all the different parts of the program work and a brief
introduction to the “glue” that puts them together (the client libraries), it’s worth taking a
look at a basic example to illustrate how each of these components work together to show
the platform at work.
This sample is a simple application that allows users to set their status using the PHP
client library, the Facebook API, FQL, mock Ajax, and FBML. I’ll show how to do this in a
single file for the ease of the discussion (plus it’s not that complicated).
If you haven’t already done so, set up a new application because you’ll need an API key
and secret. You’ll also need to set up your client libraries. If you need help with either of
these, refer to Chapter 2.
The first step is to create a new page. If you have pointed your callback URL to
http://www.foobar.com/facebook, you’ll create a new index.php file in the facebook folder of
your web root. In that page, you first need to set up a few variables:
 $facebook_config['debug'] = false;
 $facebook_config['api_key'] = '<your_api_key>';
 $facebook_config['secret_key'] = '<your_secret_key>';
 $facebook = new Facebook($facebook_config['api_key'],
 $user = $facebook->require_login();
This simply sets up some constants (api_key and secret_key) and instantiates a facebook
object (which includes an instance of the API REST client). You’ll notice that this doesn’t
actually do anything, other than create a new facebook object and gets the user ID (UID), so
let’s add something to the page:
<div style="padding:5px;">
 <fb:name uid="<?= $user?>" firstnameonly="true" capitalize="true" />
 <p>What's your status?</p>
66 Learning Facebook Platform Fundamentals
 <input type="text" name="status" value="confused" />
 <input type="submit"
 clickrewriteurl="<your_callback_url>" />
 <div id="curr_status"></div>
You’ll notice that you use the user variable you set in the PHP code to display the user’s
name. You also set a mock Ajax call to populate the empty preview div. All that’s needed
now is to write some code to handle updating the status:
 // check permissions
 $has_permission =
 //update status
 array("status" => $_REQUEST['status']));
 // grab the status
 $fql = "SELECT status FROM user WHERE uid=" . $user;
 $query_result = $facebook->api_client->fql_query($fql);
 $status = $query_result[0]['status']['message'];
 echo("<p>Your status is now: <strong>" . $status . "</strong></p>");
 } else {
 $url = '<a href="http://www.facebook.com/authorize.php?api_key=';
 $url += $api_key . '&v=1.0&ext_perm=status_update">Click here</a>';
 echo('<p style="font-size:14px;"> ');
 echo('D\'oh...it doesn\'t look like you have permissions to change your
 status. ' . $url . ' to add the permissions to update your
Learning Facebook Platform Fundamentals 67
Because updating the user’s status requires additional permissions, you’re first checking
the permissions for the user. If the user has permission, you update the status using an API
call, and then you query Facebook with FQL to make sure that the status you just set is in
fact the current status. Then you display it within the curr_status div.
When you put all these parts together, you get the following:
* @title index.php
* @description Simple status updater
$facebook_config['debug'] = false;
$facebook_config['api_key'] = '<your_api_key>';
$facebook_config['secret_key'] = '<your_secret_key>';
$facebook = new Facebook($facebook_config['api_key'],
$user = $facebook->require_login();
 // check permissions
 $has_permission = $facebook->api_client->call_method(
 //update status
 "facebook.users.setStatus", array("status" => $_REQUEST['status'])
68 Learning Facebook Platform Fundamentals
 // grab the status
 $fql = "SELECT status FROM user WHERE uid=" . $user;
 $query_result = $facebook->api_client->fql_query($fql);
 $status = $query_result[0]['status']['message'];
 echo("<p>Your status is now: <strong>" . $status . "</strong></p>");
 }else {
 $url = '<a href="http://www.facebook.com/authorize.php?api_key=';
 $url += $api_key . '&v=1.0&ext_perm=status_update">Click here</a>';
 echo('<p style="font-size:14px;"> ');
 echo('D\'oh...it doesn\'t look like you have permissions to change your
 status. ' . $url . ' to add the permissions to update your
<div style="padding:5px;">
 <fb:name uid="<?= $user?>" firstnameonly="true" capitalize="true" />
 <p>What's your status?</p>
 <input type="text" name="status" value="confused" />
 <input type="submit" clickrewriteid="curr_status"
 clickrewriteurl="<your_callback_url>" />
 <div id="curr_status"></div>
This simple application shows several of the aspects I covered in this chapter in actual
Learning Facebook Platform Fundamentals 69
Note ➡ The PHP client library includes a sample application named Footprints. This is a great application
that shows how an entire Facebook application is put together.
Things to Remember
The Facebook platform has some quirks since the code you write is interpreted through
Facebook. You might notice that when you create a form, Facebook creates several
additional input fields in your form. These are used by Facebook to process your input but
will be in there.
And, as another reminder, FBML isn’t HTML! Although you can use many of the
familiar tags in FBML as you have in HTML, there are differences in the way in which tags
are processed. For instance, you might have noticed that there isn’t a <link> tag in FBML.
As you might have guessed, this limits your ability to use external CSS files for your
application (Facebook also strips @import too). You have a couple of options to work
around this limitation.
First, you can embed your CSS in the page using the <style> tag. Generally this isn’t a
big deal if you have a small application, but as your application grows, this becomes less
manageable. A second method is to “fake” the style. Instead of using the <link> tag to point
to your style file(s), you can create your style file as you normally would and include it
within <style> tags in your PHP code. For instance:
 <?php require("style.css") ?>
This snippet will effectively include the style files for your application. You can also
use the <fb:ref> tag to pull the entire style sheet (including the <style> tags). The best
choice, of course, depends on your application, environment, and what you want to code.
If you look at the source for your generated page, you’ll also notice that Facebook
prepends your application key to the variables. For instance, if you define a style class of
.foo, it, and every reference to this class, will be rewritten to .yourAppKey_foo.
This chapter covered the different parts of the Facebook platform. The main technologies in
the platform consist of a REST API for data interchange, a language to querying
information from Facebook’s databases, and a language to render certain portions of the
70 Learning Facebook Platform Fundamentals
Facebook platform to users (FBML). There are additional parts to the language that are
more complex, such as Facebook JavaScript, and that are useful, but they’re not a core part
of the platform (that is, you don’t need to use FBJS to develop your applications). The
chapter also touched on the client libraries, which play an important part in gluing the
Facebook platform to your development language. I also showed how to create a basic,
functional application that updated the user’s status message. To do this, you used an
FBML form, mock Ajax, FQL, the PHP client library, and calls to the API.
In the next chapter, I’ll kick things up a bit and show how to develop a more robust,
complete application. I’ll not only cover user interface design and development issues, but
I’ll also briefly discuss ways to monetize your application and where to go to find help
when (or for you optimists, should) you get stuck. You’ll use an RDBMS to keep track of
user interactions, track usage with Google Analytics, and set up some useful libraries for
code reuse.

No comments