- Application Dashboards and Counters
- Navigating and Showcasing Your Application Using Tabs
- Dynamic Content and the Facebook JavaScript (FBJS) Library
- Summary
Navigating and Showcasing Your Application Using Tabs
In the early days of Facebook, a number of "integration points" were available to developers to showcase their applications. These integration points included profile boxes, news feeds, and notifications. As a greater mass of developers started using the platform, Facebook quickly became a dumping ground for spam because insufficient controls and policies failed to prevent malicious developers abusing the platform. Today, Facebook has become a lot more of a controlled environment, which means that many developers have been forced away, but many others have gone on to produce really impressive applications. With the introduction of Games and Applications dashboards alongside a unified stream social application, developers have to focus a lot more of their attention on users' experiences.
Facebook officially deprecated boxes and application info sections, which left application tabs as the only way for users to showcase their favorite applications on their profile. There are still modifications being made to how application tabs will be rendered, but the information in this section should give you enough information to start implementing them in conjunction with your Facebook applications. The deprecation has meant that many methods have been removed from the API, including the following:
- profile.getFBML
- profile.getInfo
- profile.getInfoOptions
- profile.setFBML
- profile.setInfo
- profile.setInfoOptions
If you are a new Facebook developer, the changes will mean that you now only have a single integration point to worry about. For developers who have been working with the platform for a longer period of time, these changes have been met with some negativity. Ultimately, however, these should improve the platform. They also allow you to focus more on users' experience of your applications and will be replaced by newer features as time goes by.
Configuring and Installing an Application Tab
Application tabs are displayed within Facebook next to a user's Wall, Info, and Photos tabs, and must be added explicitly by the user. An application tab is currently 520 pixels wide and can be used to render information pulled directly from your application servers as either an <iframe> or FBML. Other features of application tabs are that they can be used to load AJAX but cannot autoplay Adobe Flash, onload JavaScript, or use <iframes>. When interacting with an application tab on a friend's profile, a user's identifier is passed within an $facebook->fb_params["user"] parameter alongside the owner's identifier, which is passed within an $facebook->fb_params["profile_user"] parameter. An example of how these two parameters can be used is shown in the next section.
Because application tabs are used within the Facebook environment, their location must be set relatively to a canvas page URL. And because Facebook Platform website integration has been the focus of this book, a canvas page URL has not yet been set. We can rectify this by navigating to the "Canvas" tab of your application's settings and by providing a unique base URL prefixed by http://apps.facebook.com/. You should also set a canvas callback URL, which is the file or directory on your web server that will be served by Facebook as content for internal canvas pages. For example, if you set your canvas page URL to http://apps.facebook.com/myfacebookapp/ and your canvas callback URL to http://myfacebookapp.com/canvas/, that means that if a user visits http://apps.facebook.com/myfacebookapp/foo.php, it will be rendered from http://myfacebookapp.com/canvas/foo.php. Before continuing, check that the render method on the "Canvas" tab is set to "IFrame" because the Facebook Platform library will be used in this section.
For this chapter, you should create a new directory called canvas within your existing file structure from Chapters 5, 6, and 7, and upload two files, index.php and tab.php, along with an xd_receiver.htm file. Ensure that the references to the Facebook API PHP client library in index.php and tab.php are relative to your existing directory structure. The code in Listing 8.1 demonstrates a sample Facebook canvas page showing a simple greeting along with a user's identifier and name.
Listing 8.1. The index.php File Demonstrating a Simple Facebook Canvas Page
1 <?php 2 include "../config.php"; 3 include "../functions.php"; 4 include "../facebook-platform/php/facebook.php"; 5 $facebook = new Facebook(API_KEY, SECRET); 6 $user = $facebook->get_loggedin_user(); 7 ?> 8 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 9 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml"> 10 <head> 11 <title>Test Tube</title> 12 </head> 13 <body> 14 <h1>Canvas Page – Test Tube</h1> 15 <?php echo "<p>User Identifier: ".($user ? $user : "Unknown"). "</p>"; ?> 16 <?php echo '<p>Facebook Name: <fb:name uid="'.$user.'" useyou="false"></fb:name></p>'; ?> 17 <script src="https://static.ak.connect.facebook.com/js/api_lib/ v0.4/FeatureLoader.js.php" type="text/javascript"></script> 18 <script type="text/javascript"> 19 FB.init("<?php echo API_KEY; ?>", "xd_receiver.htm"); 20 </script> 21 </body> 22 </html>
This basic page will be rendered inside an <iframe>, which means that the Facebook PHP client library alongside the client-side Facebook Platform library will be utilized. The PHP library and configuration files are included on lines 2 to 5, and the current user is assigned on line 6. Because any Facebook user can view this page, it might be that you do not have a $user available. Therefore, this must be tested on line 15. To require that a user has logged in when visiting your canvas page, you add $facebook->require_login(); before the call on line 6. The Facebook Platform library is included on line 17 and initialized on line 19, referencing the recently uploaded xd_receiver.htm file. Save the code in Listing 8.1 as index.php and upload it to your canvas directory, which should be set as your canvas callback URL. If you visit your canvas page URL, you should be presented with a page similar to that shown in Figure 8.3.
Figure 8.3 Example canvas page for the Test Tube application.
Unlike pages within a canvas, which can be an <iframe>, your tab.php file must be rendered as valid FBML, which is demonstrated by the following code by wrapping content within two <fb:fbml> tags:
<fb:fbml> <h1>Tab Page - Test Tube</h1> <p>Hello, World!</p> </fb:fbml>
The <fb:fbml> tag has an optional version parameter that, if omitted, will render the content in the latest version of FBML. To view this number, you can use the <fb:fbmlversion /> to render the version number within your application. After you've uploaded the tab.php, go back into your application's settings and enter a tab name and tab URL on the Profiles tab. In this instance, the tab URL should be set to tab.php to mirror the file you have just uploaded, and the tab name should be set appropriately. Once you have saved your settings, visit your own Facebook profile and, if you have installed your application, you should be able to click the plus sign (+) next to the Wall, Info, and Photos tabs and select the tab you just created, as illustrated in Figure 8.4.
Figure 8.4 Example application tab for the Test Tube application.
Up until now, the application tab contains only static content, and so the next section looks at how these tabs can be extended to add more personalized information tailored to its owner and viewers.
Extending an Application Tab
Before adding additional functionality, it is worth evaluating which Facebook parameters are contained within an application tab, both when viewing a friend's profile and when interacting with it (such as sending a message). When you are viewing a canvas page, the following parameters are exposed and can be accessed by using the $facebook->fb_params array:
-
in_canvas , added , in_profile_tab , and in_new_facebook
These parameters should all be set to a 1, indicating that the profile owner has added the application and that the viewer is located within the "Profile" tab. The in_new_facebook parameter is used for legacy reasons when Facebook was transitioning between old and new layouts. If the in_profile_tab is not set to 1, you should code in functionality to redirect the user to your application's canvas page or display an error message.
-
friends , locale , profile_update_time , profile_user , profile_id , and ext_perms
These parameters are associated with the profile owner and contain a comma-separated list of their friends alongside their identifiers and any extended permissions they have granted the host application.
-
request_method , time , expires , profile_session_key , api_key , and app_id
The final parameters are used when handling Facebook actions that require sessions, such as extracting the profile owner's friends. When you are using the official client libraries, parameters such as api_key are less important because the library handles much of its complexity for you.
These parameters are also accompanied by a signature that can be accessed by using $_POST["fb_sig"]. All the parameters above are made available whether the viewer has added the application or not. However, if users intend to interact with the application (for example, submitting a form) but they have not added your application, only the following parameters will be exposed within the $facebook->fb_params array: profile; locale; in_new_facebook; sig_time; added, which will be set to 0; api_key; and app_id. In the instance, the identity of the viewer is not accessible to your application. If the viewer has added your application, this will expose the following additional parameters:
- profile_update_time, expires, session_key, and ext_perms, which were detailed earlier, although the session_key is linked with the profile viewer and not the owner.
- The viewer identifier is now also made available via the user parameter.
One of the great features about application tabs is their capability to utilize Mock AJAX calls to perform dynamic actions or to submit forms inline without having to redirect the user. In the remainder of this section, you learn how to create an application tab that enables viewers to leave a basic text comment for their friend to view. Figure 8.5 gives an example of what the final page should look like. It consists of a form that handles submissions using Mock AJAX, a comments box, and functionality to prompt users who have not already authorized your application to add it and grant extended permissions to write data to their stream.
Figure 8.5 Extended application tab for the Test Tube application.
To create the application tab shown in Figure 8.5, you must amend tab.php and create a new file for handling the comment submissions called post.php. The first step is to create the skeleton of the application tab, which will include the Facebook API PHP client library. This library will be used to validate all parameters and to ensure that the user is, in fact, viewing from within Facebook. Because the canvas callback URL exists on your own web server, it is possible for users to type that file location into their web browser outside of Facebook, which means that they must be redirected back to Facebook to prevent any malicious access. This can be achieved by adding the code in Listing 8.2 to tab.php.
Listing 8.2. Example for the tab.php File Demonstrating a Simple Application Tab
1 <?php 2 include "../config.php"; 3 include "../functions.php"; 4 include "../facebook-platform/php/facebook.php"; 5 $facebook = new Facebook(API_KEY, SECRET, $_POST["fb_sig_profile_ session_key"]); 6 $facebook->require_frame(); 7 $facebook_parameters = $facebook->get_valid_fb_params($_POST, null, "fb_sig"); 8 $profile_user = $facebook_parameters["profile_user"]; 9 if($facebook_parameters["in_profile_tab"] == 1) { 10 ?> 11 <fb:fbml> 12 // Your Application Logic Goes Here 13 </fb:fbml> 14 <?php 15 } else { 16 // Either redirect the user by setting $facebook->redirect(CANVAS_ PAGE_URL); or by presenting them with a warning saying that they are not within an application tab. 17 } 18 ?>
On line 6, a function has been added that ensures that if users type in the URL to your tab on your domain in their web browser they will be redirected back to a Facebook-hosted page. Before you add any application logic, it is worth drafting out what use your new application tab should be able to handle. Because it will have been added by a user, it is known that the user has already authorized your application, and it is possible that you can use the user identifier or other details to extract data that you hold about that user from your database and display that on your tab. Because you are provided with a session key, a number of functions can be performed on the tab itself (for example, extracting the user's friends, photos, or events). However, you will not be able to publish to the user's stream or retrieve any protected data on the user's behalf. When a user's friends access your application tab, they will be in a "passive" mode. This means you cannot access their user identifier, and so cannot determine whether they have authorized your application. Facebook provides two mechanisms for handling this issue:
- Adding a requirelogin="true" parameter to all links. This will pop up a Facebook dialog box so that users can authorize your application before proceeding if they have not already.
- When using Mock AJAX, you can add an ajax.requireLogin=1 parameter so that if viewers submit your comment form and they are not a user of your application, they will be prompted to authorize first before the comment is posted.
Both mechanisms should arrive at the same results. However, because you'll be learning about Mock AJAX in this example, the second option is used. When submitting their comment, viewers can also select whether they want to post their comment to their stream via the comments.add method. Note that you could post the response as a stream attachment or even via the Dashboard API (described earlier in this chapter). The comments.add method is used for convenience because a comments box can be placed on the application tab to show feedback to the user. Posting to their stream also requires that a viewer has granted the publish_stream extended permission, which will be prompted by the Facebook.showPermissionDialog() JavaScript function.
The comments form can be constructed using the following code, which you should use in place of the comment on line 12 of Listing 8.2:
1 <h1>Tab Page - Test Tube</h1> 2 <p id="comment_response">You can submit a test comment by using the form below. On submitting the form you will be prompted to grant permission to write to your stream which will enable your comment to be submitted.</p> 3 <form> 4 <p><label for="comment_text">Comment Text: </label><input type="text" name="comment_text" id="comment_text" value="" size="50" maxlength="140" /></p> 5 <p><label for="publish_comment">Publish To Stream: </label><input type="checkbox" name="publish_comment" id="publish_comment" /></p> 6 <p><input type="submit" value="Publish Comment" onclick=" submit_form('comment_response'); return false;" onsumbit="return false" /></p> 7 </form> 8 <h2>Comments</h2> 9 <div id="comments_box"> 10 <fb:comments xid="c_<?php echo $profile_user; ?>" canpost="true" candelete="true"></fb:comments> 11 </div>
The code above displays a simple prompt to the user on line 2. This prompt will be replaced when the form is submitted by either a success or error response. The form itself is defined in lines 3 to 7. It does not include traditional action and method attributes because you will be using the onclick action of the Submit button to post a comment. Form elements include a mixture of name and id attributes because their values and states need to be evaluated for validation and submission. The comments box on line 10 is wrapped inside a <div> because when a user submits a comment there is no way of "refreshing" its contents without refreshing the application tab. The xid of the <fb:comments> FBML element is set to that of the profile owner and is prefixed by a c_, because Facebook sometimes has issues displaying comments boxes that are purely numeric.
The next element that needs to be created is the JavaScript function submit_form(), which includes the id of the element to update after submission. The JavaScript for this example is split into two parts. The first detects whether comment text was added and whether viewers have chosen to publish their comment to their stream. If both are true, they are presented with a Permissions dialog box to grant extended permissions. If permissions are granted, a successful callback will be triggered, and the comment will be posted to their stream. If denied, the comment will still be posted but will not appear in their stream. The second part is the Mock AJAX itself, which is used to submit the comment and update the user interface. The submit_form() function looks like this and should be placed inside a <script type="text/javascript"> element:
1 function submit_form(form) { 2 comment_text = document.getElementById("comment_text").getValue(); 3 if(!comment_text == "") { 4 publish_comment = document.getElementById("publish_comment"). getChecked(); 5 if(publish_comment) { 6 Facebook.showPermissionDialog( 7 "publish_stream", 8 function(response) { 9 if(response) { do_ajax(form, publish_comment); } 10 else { 11 do_ajax(form, false); 12 document.getElementById("publish_comment").setChecked(false); 13 } 14 } 15 ); 16 } else { 17 do_ajax(form, false); 18 } 19 } else { 20 document.getElementById("comment_text").setStyle({color: "white", background: "red"}); 21 } 22 }
Facebook's implementation of JavaScript, FBJS, is slightly different to JavaScript in handling variable names. In all instances, variables are prefixed by your application ID, which creates a more controlled and sandboxed environment that prevents malicious screen refreshes and other potentially dangerous scripting abilities. Some useful FBJS commands are shown on line 2 for getting the value of a text box, on lines 4 and 12 for getting and setting the state of a check box, and on line 20 for setting the style of a text field. Further details are available in the next section for how to add event listeners and other advanced functionalities to your application tab. The Facebook.showPermissionDialog() function on lines 6 to 15 is broken down as follows:
- Line 7 defines the extended permission or permissions that are being requested. In this instance, you require only the publish_stream permission, but multiple permissions can be requested by supplying a string of comma-separated values.
- Lines 8 to 14 are the callback function, which is invoked if the user allows the permission that leads to the call on line 9. If the user denies permission or closes the Permissions dialog box, the response will be null. This will still submit the comment but will ensure that it does not attempt to publish to their stream. Because this function is being called as a result of the user checking the Publish Comment check box and then being denied, the check box is set to "unchecked" to improve user experience should the user attempt to submit again. Both callback paths will call a do_ajax() function (detailed below).
The remainder of the submit_form() function is to handle if users do not want to publish to their stream. Under this scenario, the do_ajax() function is called, much like if they deny the publish_stream extended permission. If they do not provide any comment text, the background of the text field will be set to red and the text to white. The do_ajax() functions should be placed below submit_form() and contains the following code:
1 function do_ajax(div, publish_comment) { 2 comment_text = document.getElementById("comment_text").getValue(); 3 if(!comment_text == "") { 4 var ajax = new Ajax(); 5 ajax.responseType = Ajax.JSON; 6 ajax.ondone = function(data) { 7 document.getElementById(div).setInnerFBML(data.fbml_response); 8 document.getElementById("comments_box"). setInnerFBML(data.fbml_comments); 9 document.getElementById("comment_text").setValue(""); 10 document.getElementById("comment_text").setStyle({ color: "black", background: "white" }); 11 } 12 ajax.onerror = function() { 13 document.getElementById(div).setInnerFBML('<fb:error message="There was an error submitting the form." />'); 14 } 15 var params = { 16 "comment_text": comment_text, 17 "owner": <?php echo $profile_user; ?>, 18 "publish_comment": publish_comment 19 }; 20 ajax.requireLogin = 1; 21 ajax.post("<?php echo CANVAS_CALLBACK_URL; ?>/post.php", params); 22 } 23 }
As with the submit_form() function, the do_ajax() function first tests to see that comment text has been entered. If it hasn't been, it will not submit any data to Facebook. On line 4, an AJAX object is created, and its responseType is set on line 5. The responseType can be set to Ajax.JSON, Ajax.RAW, or Ajax.FBML, which dictates the format in which the AJAX object expects data to be returned. The most flexible format is Ajax.JSON, which will be demonstrated in the example in this chapter. Lines 7 and 8 use two JSON strings, fbml_reponse and fbml_comments, which will become clear after exploring the server-side file generating the response. There are two cases for AJAX requests, which are ajax.ondone and ajax.onerror for handling successful or other responses. The ajax.ondone function on lines 6 to 11 is used to update the comments_box and for resetting the Comments text field to its original state. The final part of the function is shown on lines 15 to 21, which are used to set up POST parameters, comment_text, owner, and publish_comment, to require that users have authorized the application and to actually post the data.
Your post.php is used to perform specific server-side Facebook functions and to return the response back to the do_ajax() function. The CANVAS_CALLBACK_URL parameter that was set within the config.php should include the canvas directory to ensure that the post.php file can be found. Listing 8.3 defines an example post.php file. This should be uploaded to your web server alongside tab.php and index.php.
Listing 8.3. Example post.php File Demonstrating Adding a Comment and Returning Data Back to an Application Tab
1 <?php 2 include "../config.php"; 3 include "../functions.php"; 4 include "../facebook-platform/php/facebook.php"; 5 $facebook = new Facebook(API_KEY, SECRET); 6 $facebook_parameters = $facebook->get_valid_fb_params($_POST, null, "fb_sig"); 7 if(empty($facebook_parameters)) { 8 $facebook->redirect(CANVAS_PAGE_URL); 9 exit; 10 } 11 if($facebook_parameters["is_ajax"] == 1) { 12 $owner = $_POST["owner"]; 13 } else { 14 $owner = $facebook_parameters["profile"]; 15 } 16 $viewer = $facebook_parameters["user"]; 17 $comment_text = $_POST["comment_text"]; 18 $publish_comment = $_POST["publish_comment"]; 19 $facebook->set_user($viewer, $facebook_parameters["session_key"]); 20 $json = array(); 21 $json["fbml_comments"] = '<p>The page <a href="http://www.facebook.com/ profile.php?id='.$owner.'&v=app_'.$facebook_parameters["app_id"].'"> must be refreshed</a> to view recently-submitted comments.</p>'; 22 try { 23 $title = "Test Tube"; 24 $url = CANVAS_PAGE_URL; 25 $comment = $facebook->api_client->comments_add("c_".$owner, $comment_text, $viewer, $title, $url, $publish_comment); 26 $json["fbml_response"] = '<fb:success message="Your comment was added and will be viewable the next time you visit this tab." />'; 27 } 28 catch(Exception $e) { 29 $json["fbml_response"] = '<fb:error message="'.$e->getMessage(). '" />'; 30 } 31 echo json_encode($json); 32 ?>
As with the tab.php file, you must cater for the fact that your post.php file will be accessed externally, which is the reason for including lines 7 to 10. Because Mock AJAX is being used, Facebook adds another parameter called is_ajax but does not pass the profile parameter, which is why the owner POST parameter was set within the do_ajax() function. Other parameters are set on lines 16 to 18, and then the profile viewer is set as the active user on line 19. An empty array is created on line 20, which is finally converted to a JSON string on line 31 and which is returned to do_ajax(). As an example, line 21 is the text that replaces the initial comments_box container and is accessed within do_ajax() using data.fbml_comments. If you want to return data that is to be set using setInnerFBML, it must be prefixed with fbml_ within the $json parameter. The comments.add method is called on line 25 using the comment_text, and the final parameter dictates whether the comment is published to the viewer's stream.
After you have created the post.php file, you should upload it to your web server, and you should be ready to test out your new application tab. From here, you could try out another publishing method such as stream.publish or add additional functionality such as listing the owner's friends who have commented or displaying richer comments that include images. The final section looks at how to use the FBJS, and in particular the Animation library, which can be used to create "tweening" CSS fading background colors and styles, to hide and show block-level elements, and to ease animations for smoother transitions.