Working with the Facebook API ! Complete information on it

Working with the Facebook API

Working with the Facebook API In This Chapter Discovering how to call the Facebook API Working with the Facebook API results Knowing how to retrieve friend, event, group, and pages info Working with user data Want to take a surefire “geek developer” test? Okay, here we go. . . . On a scale from 1 to 10, when I say “API,” what is your level of excitement? If you said a number higher than 8, I suspect that you’re probably geek material. But, if so, don’t feel bad. . . . The truth is, whether you get excited about application programming interfaces (APIs) or not, an API is one of the most powerful tools available — enabling a Web programmer to tap into an otherwise impenetrable Web service. The Facebook API is the gateway to integrating your application with the Facebook Platform. You can retrieve a boatload of user, friend, event, group, and page data through its many methods. In this chapter, I introduce you to these API methods, show you how to call them, and demonstrate what to do with the results. And, whether you are a geek developer or not, I believe you’ll be excited when you see the power that’s available through this programming interface. Calling the Facebook API You can think of the Facebook API as a folder of specific questions that you can ask Facebook and commands that you can tell it to do. Can I get a list of friends for the current user? Or, can you send this story to friends of the user? The API defines those things that Facebook will let you ask or let you tell it to do. 08_277959-ch03.qxp 5/5/08 11:26 AM Page 49 Each programming language — be it PHP, Java, C++, or whatever — that is used to access the Facebook API has a language-specific syntax for calling it. Using PHP, for example, every API call is made by calling a method from the $facebook->api_client object. This object is created when you establish a Facebook session and instantiate the $facebook object using initialization code, such as the boilerplate code shown in Listing 3-1. Listing 3-1: appinclude.php require_login(); // Exception handler for invalid session_keys try { // If app is not added, then attempt to add if (!$facebook->api_client->users_isAppAdded()) { $facebook->redirect($facebook->get_add_url()); } } catch (Exception $ex) { // Clear out cookies for app and redirect user to a login prompt $facebook->set_user(null, null); $facebook->redirect($appcallbackurl); } ?> The official Facebook API documentation lists the API in a standard dot notation syntax, such as events.get. However, to use these methods, you have to translate them into the appropriate syntax for each language. The PHP client library, for example, replaces the dot with an underscore. So, for example, events.get is actually called with the following: $facebook->api_client->events_get() Tables 3-1 through 3-12 list each of the API methods organized by group. You can find more information on these and other methods in the online documentation located at http://wiki.developers.facebook.com/index. php/API. 50 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 50 Table 3-1 Users Methods Method Description users.getInfo Gets user-specific information users.getLoggedInUser Gets the current user ID users.hasAppPermission Checks whether the logged-in user has opted in to an extended application permission with the current application (unofficial at time of writing) users.isAppAdded Checks to see whether the logged-in user has added the calling application users.setStatus Updates a user’s Facebook status (unofficial at time of writing) Table 3-2 Friends Methods Method Description friends.areFriends Checks to see whether specified users are friends with each other friends.get Gets a list of friends for the current user friends.getAppUsers Gets a list of friends of the user who are signed up with the calling application friends.getLists Gets the current user’s Facebook friend lists Table 3-3 Events Methods Method Description events.get Returns events that match specified criteria events.getMembers Returns members of an event Table 3-4 Groups Methods Method Description groups.get Gets groups based on specified criteria groups.getMembers Gets members of a group Chapter 3: Working with the Facebook API 51 08_277959-ch03.qxp 5/5/08 11:26 AM Page 51 Table 3-5 Photos Methods Method Description photos.addTag Adds a tag to a photo photos.createAlbum Creates a new album photos.get Gets photos based on supplied criteria photos.getAlbums Gets metadata on photo albums photos.getTags Gets a set of tags on specified photos photos.upload Uploads a photo Table 3-6 Pages Methods Method Description pages.getInfo Retrieves Facebook pages visible to the user based on the specified criteria pages.isAdmin Checks whether current user is the admin for a page pages.isAppAdded Checks whether a specified page has added the application pages.isFan Checks whether a specified user is a fan of a page Table 3-7 Feed and Notifications Methods Method Description feed.publishStoryToUser Publishes a News Feed story to the current user feed.publishActionOfUser Publishes a Mini-Feed story to current user and publishes News Feed stories to the friends of that user feed.publishTemplatizedAction Publishes a Mini-Feed story to a user and News Feed stories to friends/fans, or publishes a MiniFeed story to the current page 52 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 52 Method Description notifications.get Gets outstanding Facebook notifications for current user notifications.send Sends a notification to one or more users notifications.sendEmail Sends an e-mail to one or more users of the application See Chapter 9 for more on publishing stories and notifications. Table 3-8 Profile Methods Method Description profile.setFBML Sets the FBML for a user’s profile for current application, including the content for the profile box, profile actions, and the mobile device profile box profile.getFBML Gets the FBML markup that is currently set for a user’s profile of current application Table 3-9 Administrative and Authentication Methods Method Description admin.getAppProperties Returns properties of a Facebook application admin.setAppProperties Sets property values of a Facebook application auth.createToken Creates a temporary authentication token that is placed in the Facebook session when the user logs in (use with Desktop applications) auth.getSession Returns the session key See Chapter 10 for info on how to use these administrative and authentication methods. Chapter 3: Working with the Facebook API 53 08_277959-ch03.qxp 5/5/08 11:26 AM Page 53 Table 3-10 FBML and FQL Methods Method Description fbml.refreshImgSrc Fetches and recaches an image specified by an absolute URL fbml.refreshRefUrl Fetches and recaches content specified by an absolute URL fbml.setRefHandle Associates a “handle” with FBML markup content (used with fb:ref) fql.query Evaluates an FQL query See Chapters 4 and 5 for more on working with these methods. Table 3-11 Local Cookie Storage Methods Method Description data.getCookies Returns cookies for a user and application data.setCookies Sets a cookie for a user and application Table 3-12 Marketplace Methods Method Description marketplace.createListing Creates or modifies a listing in the Marketplace for the currently logged-in user if the user has granted the app the create_ listing permission marketplace.getCategories Gets all Marketplace categories marketplace.getListings Gets Marketplace listings by specified criteria marketplace.getSubCategories Gets Marketplace subcategories for a particular category marketplace.removeListing Removes a listing from Marketplace for the current user marketplace.search Searches Marketplace for listings filtering by category, subcategory, and a query string 54 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 54 Evaluating What Comes Back from Facebook When you call a Facebook API method, your results normally come back in either XML (the default) or JSON format. (However, if you are using PHP, hold tight. I’ll show you in a moment that you can also work with the results as PHP arrays.) The native response format is XML. Consider, for example, the friends. get() method. When I call this method, an XML response is returned containing the user IDs of the current logged-in user’s friends: 55714303 530377451 530771206 685578792 693048091 Depending on the client library you use, you may need to process the XML document that is returned. You can also specify JSON as the results format by indicating your preference as a parameter in the API call. For example, the friends.get() method would return the user IDs in JSON format: [55714303,530377451,530771206,685578792,693048091] When you access the API using the PHP client library, results come back by default in an array. The call in PHP would be as follows: echo “
”;
print_r($facebook->api_client->friends_get());
echo “
”; Chapter 3: Working with the Facebook API 55 08_277959-ch03.qxp 5/5/08 11:26 AM Page 55 The following is output: Array ( [0] => 55714303 [1] => 530377451 [2] => 530771206 [3] => 685578792 [4] => 693048091 ) Therefore, to access the Facebook data, you would capture the response in an array: $friends = $facebook->api_client->friends_get(); echo “The first friend is $friends[0].”; The output would be The first friend is 55714303. Getting Friendly with Friends The heart and soul of Facebook is the ability for friends to interact as part of the social graph. Facebook provides three methods for working with friends: friends.get, friends.areFriends, and friends.appUsers. These are explored in the sections that follow. 56 Part II: Poking the API Get some REST The Facebook API is a REST (REpresentational State Transfer)-based interface. A typical REST operation involves sending an HTTP request to Facebook and then waiting for an HTTP response. The request contains a request method, a Uniform Resource Identifier (URI), request headers, and optionally, a request body and query string. The response contains a status code, response headers, and sometimes a response body. 08_277959-ch03.qxp 5/5/08 11:26 AM Page 56 Getting friends with friends.get The friends.get method returns the user IDs of the friends of the current user. Its PHP syntax is as follows: $facebook->api_client->friends_get() To demonstrate how this method is used, I am going to call it twice. For the first call, I simply print the results I get from Facebook. In the second, I use it in an applied example to demonstrate how you could use it in an application. Here’s the PHP code: friends_get”; echo “

”; echo “
”;
echo “

Scenario 1: Getting all friends of current user

”; echo “
Raw output:
”; print_r($facebook->api_client->friends_get()); echo “
Applied example:
”; echo “Friends of : ”; $friends = $facebook->api_client->friends_get(); echo “
    ”; foreach ($friends as $friend) { echo “
  • ”; } echo “
”; echo “

”; ?> Remember that for this and all PHP-based examples in the book, your code needs to be inside of a Facebook application you already set up (see Chapter 2) that can interact with the Facebook API. In the first call to friends_get(), the print_r command outputs the raw response. In the second call, the resulting array of friends is assigned to the $friends variable. The foreach control structure is used to iterate through each of these friends. The FBML tag fb:name is used to display the name of the friend. (See Chapter 4 for more on FBML.) Chapter 3: Working with the Facebook API 57 08_277959-ch03.qxp 5/5/08 11:26 AM Page 57 The following content is generated: Scenario 1: Getting all friends of current user Raw output: Array ( [0] => 18601493 [1] => 20715969 [2] => 55700210 [3] => 55713606 [4] => 55714303 ) Applied example: Friends of Rich Wagner: _ Louis Wagner _ Jason Wagner _ Justus Worley _ Andrew Wilson _ Josh Wyatt Evaluating friends with friends.areFriends The friends.areFriends method is used to determine whether a pair of users are friends. Its syntax is shown here: $facebook->api_client->friends_areFriends($uids1, $uids2) The $uids1 and $uids2 variables are a list of user IDs separated by commas. The corresponding IDs in each list are compared with each other — the first ID of $uids1 is evaluated with the first ID of $uids2, the second IDs against each other, and so on. If you only are comparing a single pair of IDs, you don’t need to use an array structure. The result of the evaluation is either a 1 (yes, they are friends) or 0 (no, they are most certainly not). Check out the following example in which I use friends.areFriends in three different instances. The first case compares two users by ID, and the second compares a list of users and prints the raw output. The final case displays a bulleted list that tells the results of the evaluation. Look at the following code: 58 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 58 ”; echo “

friends_areFriends

”; echo “

”; echo “

Scenario 1: Determine whether two users are friends or not

”; echo “
Raw output:
”; print_r($facebook->api_client->friends_areFriends(685578792, 531385404 )); echo “

”; $uids1 = array( 20715969, 55713606, 696951095); $uids2 = array( 705671487, 55714303, 549572223); echo “

Scenario 2: Determine whether a set of users are friends or not

”; echo “
Raw output:
”; print_r($facebook->api_client->friends_areFriends($uids1, $uids2)); echo “
Applied example:
”; $uids1 = array( 20715969, 55713606, 696951095); $uids2 = array( 705671487, 55714303, 549572223); $friendsMatch = $facebook->api_client->friends_areFriends($uids1, $uids2); echo “
    ”; echo “
  • Are and friends? {$friendsMatch[0][‘are_friends’]}
  • ”; echo “
  • Are and friends? {$friendsMatch[1][‘are_friends’]}
  • ”; echo “
  • Are and friends? {$friendsMatch[2][‘are_friends’]}
  • ”; echo “
”; echo “”; ?> As you can see from the following resulting output, the two users were not friends in the first case. The second comparison uncovered one friendship among the three tests. The final case uncovered one more friendship: friends_areFriends Scenario 1: Determine whether two users are friends or not Raw output: Array ( [0] => Array ( [uid1] => 685578792 [uid2] => 531385404 Chapter 3: Working with the Facebook API 59 08_277959-ch03.qxp 5/5/08 11:26 AM Page 59 [are_friends] => 0 ) ) Scenario 2: Determine whether a set of users are friends or not Raw output: Array ( [0] => Array ( [uid1] => 20715969 [uid2] => 705671487 [are_friends] => 0 ) [1] => Array ( [uid1] => 55713606 [uid2] => 55714303 [are_friends] => 1 ) [2] => Array ( [uid1] => 696951095 [uid2] => 549572223 [are_friends] => 0 ) ) Applied example: _ Are Ann Stephens and Chris Nope friends? 0 _ Are Sam Blackmere and Josh Wattly friends? 1 _ Are Alex Stephens and Phillip Burr friends? 0 Getting friends who are app users with friends.appUsers The friends.appUsers method is used to determine which friends of the user have added the application to their Facebook profiles. The method can be called in PHP using the following code: $facebook->api_client->friends_getAppUsers() The method has no parameters. 60 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 60 The following code makes this API call twice: ”; echo “

friends_getAppUsers

”; echo “

”; echo “

Scenario 1: Getting all friends of current user who are users of this app

”; echo “
Raw output:
”; print_r($facebook->api_client->friends_getAppUsers()); echo “
Applied example:
”; echo “App friends of :
”; $friends = $facebook->api_client->friends_getAppUsers(); echo “
    ”; if($friends){ foreach ($friends as $friend) { echo “
  • ”; } }else{ echo “
  • None of your friends are using this app.
  • ”; } echo “
”; echo “”; ?> Here is the output generated: friends_getAppUsers Scenario 1: Getting all friends of current user who are users of this app Raw output: Array ( [0] => 18601493 [1] => 20715969 [2] => 55700210 [3] => 55713606 [4] => 55714303 ) Applied example: App friends of Rich Wagner: _ Jason Verede _ Ronald Smithers _ Dooley Wilson _ Carl Manhammer _ Lefty Mulligan Chapter 3: Working with the Facebook API 61 08_277959-ch03.qxp 5/5/08 11:26 AM Page 61 Accessing Events The Facebook API offers two functions that you can use to access calendarbased events of a user — events.get and events.getMembers. Each Facebook event has a specified list of properties that are helpful to know when looking for a specific piece of information. These include: eid, name, tagline, nid, pic, pic_big, pic_small, host, description, event_type, event_subtype, start_time, end_time, creator, update_time, location, and venue (street, city, state, country, latitude, and longitude). Note that subarrays are shown in parentheses. Getting the events of a user You can retrieve the events of a user with the events.get method. To call it in PHP, you use the following syntax: $facebook->api_client->events_get($uid, $eids, $start_time, $end_time, $rsvp_status) You can use the parameters to filter the events you want to retrieve, as follows: The $uid parameter allows you to specify a user ID. If null, the current user is used. $eids is a comma-separated list of event IDs. The $start_time and $end_time parameters are for filtering based on the UTC date/time value. (The time-zone-dependent times specified by the event creator are converted to UTC and then into a UNIX timestamp, like is created with the PHP time() function, when stored in the Facebook database.) The $rsvp_status is one of four values: attending, unsure, declined, or not_replied. The following example uses events.get to get all events for the current user, all events for a specified user, and specific events by event ID. Here’s the code: ”; 62 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 62 echo “

events_get

”; echo “

”; echo “

Scenario 1: Getting all events for current user

”; echo “
Raw output:
”; print_r($facebook->api_client->events_get(null, null, null, null, null)); echo “
Applied example:
”; echo “Active events for :
”; $events = $facebook->api_client->events_get(null, null, null, null, null); echo “
    ”; if($events){ foreach ($events as $event) { echo “
  • {$event[‘name’]} - {$event[‘location’]}
  • ”; } }else{ echo “
  • No events for this user
  • ”; } echo “
”; echo “

”; echo “

Scenario 2: Getting all events for a specified user

”; echo “
Raw output:
”; print_r($facebook->api_client->events_get(55714303, null, null, null, null)); echo “
Applied example:
”; echo “Active events for :
”; $events = $facebook->api_client->events_get(55714303, null, null, null, null); echo “
    ”; if($events){ foreach ($events as $event) { echo “
  • {$event[‘name’]} - {$event[‘location’]}
  • ”; } }else{ echo “
  • No events for this user
  • ”; } echo “
”; echo “

”; echo “

Scenario 3: Getting an event by id

”; echo “
Raw output:
”; print_r($facebook->api_client->events_get(null, array(6589513372, 8182230950), null, null, null)); ?> In the first scenario, the calls to events_get uses null as the value for each parameter to get all events for the logged-in user. In the second case, a user ID is provided to get that person’s events other than the current user. Finally, the third scenario uses an array of event IDs to retrieve details for these specific events. Chapter 3: Working with the Facebook API 63 08_277959-ch03.qxp 5/5/08 11:26 AM Page 63 The events returned contain 23 properties that can be accessed from a results array. The output is as follows: events_get Scenario 1: Getting all events for current user Raw output: Array ( [0] => Array ( [eid] => 6770688818 [name] => Justy’s Birthday [tagline] => The Big Fourteen [nid] => 0 [pic] => http://profile.ak.facebook.com/object2/1209/121/s6770688818_7452. jpg [pic_big] => http://profile.ak.facebook.com/object2/1209/121/n6770688818_7452. jpg [pic_small] => http://profile.ak.facebook.com/object2/1209/121/t6770688818_7452. jpg [host] => Rich Wagner [description] => Yeah for Justy [event_type] => Party [event_subtype] => Birthday Party [start_time] => 1201921200 [end_time] => 1201928400 [creator] => 665127078 [update_time] => 1199553869 [location] => Our house [venue] => Array ( [street] => [city] => Princeton [state] => Massachusetts [country] => United States [latitude] => 42.4486 [longitude] => -71.8778 ) ) [1] => Array ( 64 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 64 [eid] => 8182230950 [name] => The Expeditionary Man Bike Tour [tagline] => ad atla simul [nid] => 0 [pic] => http://profile.ak.facebook.com/object2/396/26/s8182230950_78.jpg [pic_big] => http://profile.ak.facebook.com/object2/396/26/n8182230950_78.jpg [pic_small] => http://profile.ak.facebook.com/object2/396/26/t8182230950_78.jpg [host] => Rich Wagner [description] => [event_type] => Trips [event_subtype] => Roadtrip [start_time] => 1214661600 [end_time] => 1217026800 [creator] => 665127078 [update_time] => 1199553396 [location] => San Diego [venue] => Array ( [street] => [city] => San Diego [state] => California [country] => United States [latitude] => 32.7153 [longitude] => -117.156 ) ) ) Applied example: Active events for Rich Wagner: Justy’s Birthday - Our house The Expeditionary Man Bike Tour - San Diego Scenario 2: Getting all events for a specified user Raw output: Array ( [0] => Array ( [eid] => 6589513372 [name] => High School Ski Trip ‘08 [tagline] => Notoriously one of the best events of the year . . . [nid] => 0 [pic] => http://profile.ak.facebook.com/object2/935/61/s6589513372_8557.jpg Chapter 3: Working with the Facebook API 65 08_277959-ch03.qxp 5/5/08 11:26 AM Page 65 [pic_big] => http://profile.ak.facebook.com/object2/935/61/ n6589513372_8557.jpg [pic_small] => http://profile.ak.facebook.com/object2/935/61/ t6589513372_8557.jpg [host] => The Commons [description] => 3 Days @ Mount Sunapee, New Hampshire complete with skiing/snowboarding/snowblading, spiritual growth, hanging with friends, making new ones, and invading the game room (pool/darts/ping-pong/cards/foosball/air-hockey, etc.)! //Grab an info packet @ The Commons. //Registration & Deposit Deadline: Nov. 25th [event_type] => Trips [event_subtype] => Group Trip [start_time] => 1200094200 [end_time] => 1200283200 [creator] => 55714303 [update_time] => 1192647498 [location] => Mt. Sunapee : : : Dexter’s Inn [venue] => Array ( [street] => [city] => Sunapee [state] => New Hampshire [country] => United States [latitude] => 43.3875 [longitude] => -72.0883 ) ) [1] => Array ( [eid] => 2233964858 [name] => wedding [tagline] => my wedding [nid] => 0 [pic] => http://profile.ak.facebook.com/object/963/28/s2233964858_ 30773.jpg [pic_big] => http://profile.ak.facebook.com/object/963/28/ n2233964858_30773.jpg [pic_small] => http://profile.ak.facebook.com/object/963/28/ t2233964858_30773.jpg [host] => me and sara [description] => ryan and saras wedding day [event_type] => Other [event_subtype] => Festival [start_time] => 1192302000 [end_time] => 1192327200 66 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 66 [creator] => 513119649 [update_time] => 1170982520 [location] => my church [venue] => Array ( [street] => [city] => [state] => [country] => ) ) [2] => Array ( [eid] => 4706509087 [name] => International Talk Like a Pirate Day [tagline] => Arrrr, matey [nid] => 0 [pic] => http://profile.ak.facebook.com/object2/1197/22/s4706509087_ 7843.jpg [pic_big] => http://profile.ak.facebook.com/object2/1197/22/ n4706509087_7843.jpg [pic_small] => http://profile.ak.facebook.com/object2/1197/22/ t4706509087_7843.jpg [host] => Everyone [description] => Very self descriptive... talk like a pirate... All day. Tell everyone you know about it. [event_type] => Causes [event_subtype] => Rally [start_time] => 1190185200 [end_time] => 1190271600 [creator] => 35907261 [update_time] => 1188968989 [location] => Everywhere [venue] => Array ( [street] => [city] => [state] => [country] => ) ) Scenario 3: Getting an event by id Raw output: Chapter 3: Working with the Facebook API 67 08_277959-ch03.qxp 5/5/08 11:26 AM Page 67 Array ( [0] => Array ( [eid] => 6589513372 [name] => High School Ski Trip ‘08 [tagline] => Notoriously one of the best events of the year . . . [nid] => 0 [pic] => http://profile.ak.facebook.com/object2/935/61/s6589513372_ 8557.jpg [pic_big] => http://profile.ak.facebook.com/object2/935/61/ n6589513372_8557.jpg [pic_small] => http://profile.ak.facebook.com/object2/935/61/ t6589513372_8557.jpg [host] => The Commons [description] => 3 Days @ Mount Sunapee, New Hampshire complete with skiing/snowboarding/snowblading, spiritual growth, hanging with friends, making new ones, and invading the game room (pool/darts/ping-pong/cards/foosball/air-hockey, etc.)! //Grab an info packet @ The Commons. //Registration & Deposit Deadline: Nov. 25th [event_type] => Trips [event_subtype] => Group Trip [start_time] => 1200094200 [end_time] => 1200283200 [creator] => 55714303 [update_time] => 1192647498 [location] => Mt. Sunapee : : : Dexter’s Inn [venue] => Array ( [street] => [city] => Sunapee [state] => New Hampshire [country] => United States [latitude] => 43.3875 [longitude] => -72.0883 ) ) [1] => Array ( [eid] => 8182230950 [name] => The Expeditionary Man Bike Tour [tagline] => ad atla simul [nid] => 0 [pic] => http://profile.ak.facebook.com/object2/396/26/s8182230950_78.jpg [pic_big] => http://profile.ak.facebook.com/object2/396/26/n8182230950_78.jpg 68 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 68 [pic_small] => http://profile.ak.facebook.com/object2/396/26/t8182230950_78.jpg [host] => Rich Wagner [description] => [event_type] => Trips [event_subtype] => Roadtrip [start_time] => 1214661600 [end_time] => 1217026800 [creator] => 665127078 [update_time] => 1199553396 [location] => San Diego [venue] => Array ( [street] => [city] => San Diego [state] => California [country] => United States [latitude] => 32.7153 [longitude] => -117.156 ) ) ) Getting the members of an event The events.getMembers method is used to retrieve the members of an event based on the event ID. Here’s the PHP syntax: $facebook->api_client->events_getMembers($eid) In the following example, I get all the members of an event and simply output the array results: events_getMembers”; echo “

”; echo “

Scenario 1: Getting all members of an event (grouped by status)

”; echo “
Raw output:
”; echo “
”;
print_r($facebook->api_client->events_getMembers(6589513372));
echo “
”; ?> Chapter 3: Working with the Facebook API 69 08_277959-ch03.qxp 5/5/08 11:26 AM Page 69 The results are shown here: events_getMembers Scenario 1: Getting all members of an event (grouped by status) Raw output: Array ( [attending] => Array ( [0] => 729427552 [1] => 787340441 [2] => 644453917 [3] => 530987125 [4] => 561260764 [5] => 588343354 ) [unsure] => Array ( [0] => 577940038 [1] => 685578792 ) [declined] => Array ( [0] => 501777965 [1] => 215200237 [2] => 719441622 [3] => 530377451 [4] => 705671487 ) [not_replied] => ) The results are provided in PHP in an associative array whose elements are grouped by the rsvp_status of the members. Consider a second example in which I work with the resulting array that is returned. Check out the code: ”; echo “

Scenario 1: Getting all members of an event (grouped by status)

”; echo “
Applied example:
”; $events = $facebook->api_client->events_get(null, 6589513372, null, null, null); echo “Members for {$events[0][‘name’]}
”; $members = $facebook->api_client->events_getMembers(6589513372); echo “Attending:
”; 70 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 70 echo “
    ”; if ($members[‘attending’][0]) { foreach ($members[‘attending’] as $member) { echo “
  • ”; } } else { echo “None”; } echo “
”; echo “Maybe, maybe not:
”; echo “
    ”; if ($members[‘unsure’][0]) { foreach ($members[‘unsure’] as $member) { echo “
  • ”; } } else { echo “None”; } echo “
”; echo “Not attending:
”; echo “
    ”; if ($members[‘declined’][0]) { foreach ($members[‘declined’] as $member) { echo “
  • ”; } } else { echo “None”; } echo “
”; echo “Unsure:
”; echo “
    ”; if ($members[‘not_replied’][0]) { foreach ($members[‘not_replied’] as $member) { echo “
  • ”; } } else { echo “None”; } echo “
”; echo “”; ?> The events_get method is used to retrieve the event details. I then use this info to display the event name using $events[0][‘name’]. I then use events_getMembers to retrieve the members of the event in the $members array. The first foreach looping structure iterates through the $members[‘attending’] elements (the members whose rsvp_status is attending). The member’s name is output as a bulleted list item. The next three foreach loops create similar lists for these other elements. Chapter 3: Working with the Facebook API 71 08_277959-ch03.qxp 5/5/08 11:26 AM Page 71 Be sure to notice the test I conduct on the associative arrays before using the foreach looping. Because Facebook can return an empty list for each of these membership status values, you would get a PHP error if you try to perform a foreach loop on an empty list. To make life even more interesting for developers, you cannot simply check count($members[‘attending’]). An empty subarray still returns a count of 1, making it impossible to distinguish between a status list of 1 and 0 members using count(). Instead, I am using an if...else block to evaluate the first element of each subarray to ensure that it is not blank. The output is as follows: Applied example: Members for High School Ski Trip ‘08 Attending: Jan Brythe Ashley Rolands Em Martellin Ty Prancer Emelie MacTigue Elizabeth Lewis Maybe, maybe not: Jared Wagner Ashley Marie Martell Not attending: Amanda Prancer Jal Hutchinson Steve Apple Jordan Wagner Betty Noel Unsure: Getting Cozy with Groups Facebook groups are networks of Facebook users who join together for a particular common interest. You can work with groups much like you work with events (see the section “Accessing Events,” earlier in this chapter). You have two methods for accessing Facebook group-related information — getting 72 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 72 groups of a user with groups.get and getting members of a particular group with groups.getMembers. These two functions are discussed in the following sections. Each Facebook group has several data properties that you may wish to retrieve including, gid, name, nid, description, group_type, group_ subtype, recent_news, pic, pic_big, pic_small, creator, update_ time, office, website, and venue (street, city, state, country). Getting groups with groups.get You can retrieve groups with the groups.get method. In PHP, you call it by using the following syntax: $facebook->api_client->groups_get($uid, $gids) The $uid parameter allows you to retrieve groups based on a user ID. The $gids parameter optionally enables you to retrieve based on an array of group IDs. The following example shows four different scenarios of using groups_get(): getting all groups for the current user, all groups for a specific user, info for a specific group, and info about several groups. Note how the different results are achieved through the parameters used. Here’s the code: groups_get”; echo “

”; /* Scenario 1 */ echo “

Scenario 1: Getting all groups for current user

”; $uid = null; $gid = null; $groups = $facebook->api_client->groups_get($uid,$gid); echo “
Raw output:
”; echo “
”;
print_r($groups);
echo “
”; echo “
Applied example:
”; echo “Active events for :
”; echo “
    ”; Chapter 3: Working with the Facebook API 73 08_277959-ch03.qxp 5/5/08 11:26 AM Page 73 if($groups){ foreach ($groups as $group) { echo “
  • {$group[‘name’]}
  • ”; } }else{ echo “
  • User is not a member of any groups
  • ”; } echo “
”; echo “

”; /* Scenario 2 */ echo “

Scenario 2: Getting all groups for a specific user

”; $uid = 585166905; $gid = null; $groups = $facebook->api_client->groups_get($uid,$gid); echo “
Raw output:
”; echo “
”;
print_r($groups);
echo “
”; echo “

”; /* Scenario 3 */ echo “

Scenario 3: Getting info for a specific group

”; $uid = 585166905; $gid = 17342247576; $groups = $facebook->api_client->groups_get($uid,$gid); echo “
Raw output:
”; echo “
”;
print_r($groups);
echo “
”; echo “

”; /* Scenario 4 */ echo “

Scenario 4: Getting info about several groups

”; $uid = null; $gid = array(2208108698,2210253039,17342247576); $groups = $facebook->api_client->groups_get($uid,$gid); echo “
Raw output:
”; echo “
”;
print_r($groups);
echo “
”; ?> 74 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 74 The results are as follows: groups_get Scenario 1: Getting all groups for current user Raw output: Array ( [0] => Array ( [gid] => 2208108698 [name] => HECK YES I QUOTE MOVIES [nid] => 0 [description] => None [group_type] => Entertainment & Arts [group_subtype] => Movies [recent_news] => [pic] => http://profile.ak.facebook.com/object/1961/40/s2208108698_ 37065.jpg [pic_big] => http://profile.ak.facebook.com/object/1961/40/ n2208108698_37065.jpg [pic_small] => http://profile.ak.facebook.com/object/1961/40/ t2208108698_37065.jpg [creator] => [update_time] => 1173885432 [office] => [website] => [venue] => Array ( [street] => [city] => [state] => [country] => ) ) [1] => Array ( [gid] => 8900080125 [name] => Six Degrees Of Separation - The Experiment [nid] => 0 [description] => You are invited to take part in the most ambitious facebook experiment ever... Using the Six Degrees of Separation theory, I want to see if it’s possible to contact every single person on facebook. The theory states that everybody on this planet is separated by only six other people. (it could be argued that we’re all only six degrees from the entire Indian Cricket team!). Chapter 3: Working with the Facebook API 75 08_277959-ch03.qxp 5/5/08 11:26 AM Page 75 [group_type] => Just for Fun [group_subtype] => Facebook Classics [recent_news] => Jan 10 (19:40) [pic] => http://profile.ak.facebook.com/object2/1538/101/ s8900080125_4899.jpg [pic_big] => http://profile.ak.facebook.com/object2/1538/101/ n8900080125_4899.jpg [pic_small] => http://profile.ak.facebook.com/object2/1538/101/ t8900080125_4899.jpg [creator] => [update_time] => 1199994165 [office] => [website] => www.steve-jackson.net [venue] => Array ( [street] => [city] => [state] => [country] => ) ) [2] => Array ( [gid] => 8298576990 [name] => Sheep Among Wolves [nid] => 0 [description] =>A Christian Rock band [group_type] => Music [group_subtype] => Rock [recent_news] => [pic] => http://profile.ak.facebook.com/object2/1105/5/s8298576990_ 8816.jpg [pic_big] => http://profile.ak.facebook.com/object2/1105/5/ n8298576990_8816.jpg [pic_small] => http://profile.ak.facebook.com/object2/1105/5/ t8298576990_8816.jpg [creator] => 713210144 [update_time] => 1197033084 [office] => Wagner’s House [website] => http://hs.facebook.com/profile.php?id=6653134479 [venue] => Array ( [street] => [city] => Princeton 76 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 76 [state] => Massachusetts [country] => United States [latitude] => 42.4486 [longitude] => -71.8778 ) ) Applied example: Active events for Rich Wagner: HECK YES I QUOTE MOVIES Six Degrees Of Separation - The Experiment Sheep Among Wolves Scenario 2: Getting all groups for a specific user Raw output: Array ( [0] => Array ( [gid] => 17342247576 [name] => Telecom Council of Silicon Valley [nid] => 0 [description] => [group_type] => Organizations [group_subtype] => Professional Organizations [recent_news] => The Council is taking Founding Members, filling its Board, and looking for connected and energetic people in the local telecom industry to fill key leadership positions. Drop us a line of you are interested. [pic] => http://profile.ak.facebook.com/object2/1428/65/ s17342247576_3165.jpg [pic_big] => http://profile.ak.facebook.com/object2/1428/65/ n17342247576_3165.jpg [pic_small] => http://profile.ak.facebook.com/object2/1428/65/ t17342247576_3165.jpg [creator] => 718570130 [update_time] => 1199227600 [office] => [website] => http://www.telecomcouncil.com [venue] => Array ( [street] => [city] => [state] => CA Chapter 3: Working with the Facebook API 77 08_277959-ch03.qxp 5/5/08 11:26 AM Page 77 [country] => United States ) ) Scenario 3: Getting info for a specific group Raw output: Array ( [0] => Array ( [gid] => 17342247576 [name] => Telecom Council of Silicon Valley [nid] => 0 [description] => [group_type] => Organizations [group_subtype] => Professional Organizations [recent_news] => The Council is taking Founding Members, filling its Board, and looking for connected and energetic people in the local telecom industry to fill key leadership positions. Drop us a line of you are interested. [pic] => http://profile.ak.facebook.com/object2/1428/65/ s17342247576_3165.jpg [pic_big] => http://profile.ak.facebook.com/object2/1428/65/ n17342247576_3165.jpg [pic_small] => http://profile.ak.facebook.com/object2/1428/65/ t17342247576_3165.jpg [creator] => 718570130 [update_time] => 1199227600 [office] => [website] => http://www.telecomcouncil.com [venue] => Array ( [street] => [city] => [state] => CA [country] => United States ) ) ) Scenario 4: Getting info about several groups Raw output: Array 78 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 78 ( [0] => Array ( [gid] => 2208108698 [name] => HECK YES I QUOTE MOVIES [nid] => 0 [description] => [group_type] => Entertainment & Arts [group_subtype] => Movies [recent_news] => [pic] => http://profile.ak.facebook.com/object/1961/40/s2208108698_ 37065.jpg [pic_big] => http://profile.ak.facebook.com/object/1961/40/ n2208108698_37065.jpg [pic_small] => http://profile.ak.facebook.com/object/1961/40/ t2208108698_37065.jpg [creator] => [update_time] => 1173885432 [office] => [website] => [venue] => Array ( [street] => [city] => [state] => [country] => ) ) [1] => Array ( [gid] => 2210253039 [name] => All I ever needed to know in life, I learned by reading Dr. Seuss. [nid] => 0 [description] => To all of us who have gained perspective of the world by stepping into the wondrous world of Dr Seuss when we were young. [group_type] => Just for Fun [group_subtype] => Totally Random [recent_news] => None [pic] => http://profile.ak.facebook.com/object/1345/125/s2210253039_22864. jpg Chapter 3: Working with the Facebook API 79 08_277959-ch03.qxp 5/5/08 11:26 AM Page 79 [pic_big] => http://profile.ak.facebook.com/object/1345/125/n2210253039_22864. jpg [pic_small] => http://profile.ak.facebook.com/object/1345/125/t2210253039_22864. jpg [creator] => 512826063 [update_time] => 1165737138 [office] => Whoville [website] => [venue] => Array ( [street] => [city] => [state] => [country] => ) ) ) Retrieving member info with groups.getMembers The groups.getMembers call is used to gather membership information from one or more groups. It contains a single parameter indicating the group ID ($gid) as shown in the PHP call: $facebook->api_client->groups_getMembers($gid) The call returns an associative array of user IDs, grouped by their membership status: members, admins, officers, and not_replied. Consider the following example. In the first case, it prints the raw results of the call using print_r. In the second case, the results are organized into separate bulleted lists by performing a foreach loop for each of the four membership status values: $members[‘members’], $members[‘admins’], $members[‘officers’], and $members[‘no_replies’] to print the list items. Here’s the code: groups_getMembers”; 80 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 80 echo “

”; echo “

Scenario 1: Getting all members of a group (grouped by type)

”; $gid = 8298576990; $uid = null; $members = $facebook->api_client->groups_getMembers($gid); $groups = $facebook->api_client->groups_get($uid, $gid); echo “
Raw output:
”; echo “
”;
print_r($members);
echo “
”; echo “
Applied example:
”; echo “Members for {$groups[0][‘name’]}
”; echo “Regular members:
”; echo “
    ”; if ($members[‘members’][0]) { foreach ($members[‘members’] as $member){ echo “
  • ”; } } else { echo “
  • None
  • ”; } echo “
”; echo “Administrators:
”; echo “
    ”; if ($members[‘admins’][0]) { foreach ($members[‘admins’] as $member) { echo “
  • ”; } } else { echo “
  • None
  • ”; } echo “
”; echo “Officers:
”; echo “
    ”; if ($members[‘officers’][0]) { foreach ($members[‘officers’] as $member){ echo “
  • ”; } } else { echo “
  • None
  • ”; } Chapter 3: Working with the Facebook API 81 08_277959-ch03.qxp 5/5/08 11:26 AM Page 81 echo “
”; echo “No replies:
”; echo “
    ”; if ($members[‘not_replied’][0]){ foreach ($members[‘not_replied’] as $member){ echo “
  • ”; } } else { echo “
  • None
  • ”; } echo “
”; ?> As I indicate earlier in the chapter, pay special attention to the test performed on the associative array before using foreach. The results can return an empty list for each of these membership status values. If you perform a foreach loop on one of these empty lists, you’ll get an error. To further complicate matters, you cannot simply check count($members[‘officers’]) because the empty subarray still returns a count of 1, making it impossible to distinguish between a status list of 1 and 0 members using count(). Therefore, I am using an if...else block to evaluate the first element of each subarray to ensure that it is not blank. The results are shown here: groups_getMembers Scenario 1: Getting all members of a group (grouped by type) Raw output: Array ( [members] => Array ( [0] => 532605112 [1] => 809149455 [2] => 537552695 [3] => 801079753 ) [admins] => Array ( [0] => 713210144 ) [officers] => [not_replied] => Array 82 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 82 ( [0] => 810334061 [1] => 55706757 ) ) Applied example: Members for Sheep Among Wolves Regular members: _ Dave Lazlo _ Larry More _ Rob Larice _ Tuck Laughon Administrators: _ Kels Rollings Officers: _ None No replies: _ Steve Mistry _ Syndal Dylan Facebook Pages Facebook pages provide a business, band, or artist a way to establish a presence with their customers or fans. Facebook users can become fans of pages, and applications can be added to a Facebook page. As a developer, you can work with Facebook pages using the pages.getInfo, pages.isAppAdded, pages.isAdmin, and pages.isFan methods. Each Facebook page has many data properties associated with it that you may wish to retrieve in your queries. These properties correspond to the values that the admin of the page fills in interactively through the online forms. These include page_id, name, pic_small, pic_square, pic_big, pic, pic_large, type, website, locationlocation (street, city, state, country, zip), hours, hours (mon_1_open, mon_1_close, tue_1_open, tue_1_close, wed_1_open, wed_1_close, thu_1_open, Chapter 3: Working with the Facebook API 83 08_277959-ch03.qxp 5/5/08 11:26 AM Page 83 thu_1_close, fri_1_open, fri_1_close, sat_1_open, sat_1_close, sun_1_open, sun_1_close, mon_2_open, mon_2_close, tue_2_open, tue_2_close, wed_2_open, wed_2_close, thu_2_open, thu_2_close, fri_2_open, fri_2_close, sat_2_open, sat_2_close, sun_2_open, sun_2_close), band_members, bio, hometown, genre, genre (dance, party, relax, talk, think, workout, sing, intimate, raunchy, headphones), record_label, influences, has_added_app, founded, company_overview, mission, products, release_date, starring, written_by, directed_by, produced_by, studio, awards, plot_ outline, network, season, schedule. Note that inclusive list contains many elements that are specific to particular page types. For example, a band page would have a band_members value but would leave a field like hours blank. Getting page information with pages.getInfo The pages.getInfo method is used to retrieve one or more pages based on the criteria you use in the parameters. Here’s the syntax in PHP: $facebook->api_client->pages_getInfo($pids, $fields, $uid, $type) The parameters are as follows: The $pids parameter is an array of page IDs. The $fields parameter is an array of fields you want to return. The $uid parameter is the user ID if you want to retrieve pages of a particular user. The $type parameter allows you to specify results based on the page type. The following example walks you through three scenarios of retrieving pages. The first scenario gets all the pages that the current user is a fan of, while the second example specifies a particular user ID. The final call specifies a list of page IDs to retrieve. In each case, a list of fields is specified in the $fields parameter. Check out the code: ’); echo “

pages_getInfo

”; 84 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 84 echo “

”; echo “

Scenario 1: Get all pages in which current user is a fan

”; echo “
Raw output:
”; print_r($facebook->api_client->pages_getInfo( null, array(‘page_id’, ‘name’, ‘pic_small’, ‘type’), $user, null)); echo(‘

’); echo “

Scenario 2: Get all pages in which specified user is a fan

”; echo “
Raw output:
”; $uid = ‘705396409’; print_r($facebook->api_client->pages_getInfo( null, array(‘page_id’, ‘name’, ‘pic_small’, ‘type’), $uid, null)); echo(‘

’); echo “

Scenario 3: Get info on pages specified by page_id

”; echo “
Raw output:
”; print_r($facebook->api_client->pages_getInfo( array(6829493713, 6233046685), array(‘page_id’, ‘name’, ‘pic_small’, ‘type’), null, null)); echo(‘’); ?> The results of these three method calls are as follows: Scenario 1: Get all pages in which current user is a fan Raw output: Array ( [0] => Array ( [page_id] => 6829493713 [name] => (RED) [pic_small] => http://profile.ak.facebook.com/object2/432/64/ t6829493713_3248.jpg [type] => CONSUMER_PRODUCTS ) ) Scenario 2: Get all pages in which specified user is a fan Raw output: Array ( [0] => Array ( [page_id] => 6829493222 [name] => Charleston Bikes [pic_small] => http://profile.ak.facebook.com/object2/432/64/ t6829493713_3248.jpg Chapter 3: Working with the Facebook API 85 08_277959-ch03.qxp 5/5/08 11:26 AM Page 85 [type] => CONSUMER_PRODUCTS ) ) Scenario 3: Get info on pages specified by page_id Raw output: Array ( [0] => Array ( [page_id] => 6829493713 [name] => (RED) [pic_small] => http://profile.ak.facebook.com/object2/432/64/ t6829493713_3248.jpg [type] => CONSUMER_PRODUCTS ) [1] => Array ( [page_id] => 6233046685 [name] => Ron Paul [pic_small] => http://profile.ak.facebook.com/object2/512/17/ t6233046685_4045.jpg [type] => POLITICIANS ) ) Scoping out with pages.isAppAdded You can check to see whether your application is added to a page using pages.isAppAdded. Here’s the code: $facebook->api_client->pages_isAppAdded($pid) The $pid parameter specifies a specific page ID. The call returns a 1 (true) or 0 (false). For example: ’); echo “

pages_isAppAdded

”; echo “

”; echo “

Scenario 1: Checks whether a page has added the application

”; echo “
Raw output:
”; print_r($facebook->api_client->pages_isAppAdded(‘6829493713’)); echo(‘’); ?> 86 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 86 Getting current user info with pages.isAdmin and pages.isFan The pages.isAdmin and pages.isFan methods are used to determine whether the current user is an admin or a fan of the specified page. You can call these two methods in a similar manner: $facebook->api_client->pages_isFan($pid) $facebook->api_client->pages_isAdmin($pid) The $pid parameter is a page ID of a single page. Both of these methods return a 1 (true) or 0 (false) response. Pulling User Data Facebook provides extended access to user data from inside your application. To access this data, you have four methods: users.getLoggedInUser, users.getInfo, users.isAppAdded, and users.hasAppPermission. Getting the current user with users.getLoggedInUser The users.getLoggedInUser method is used to return the user ID of the currently logged-in user. It is usually called at the beginning of a session and stored in a variety of ways to avoid calling this method multiple times. The syntax using PHP is as follows: $facebook->api_client->users_getLoggedInUser() It takes no parameters. The following example shows this method in action: $user = $facebook->api_client->users_getLoggedInUser(); echo “The user that is currently logged in is {$user}”; The result is the user’s ID: The user that is currently logged in is 665127078 Chapter 3: Working with the Facebook API 87 08_277959-ch03.qxp 5/5/08 11:26 AM Page 87 Getting info with users.getInfo The users.getInfo call enables you to retrieve user profile information based on the view of the current user. The PHP syntax is as follows: $facebook->api_client->users_getInfo($uids, $fields) The $uids parameter indicates an array of user IDs. The $fields parameter is an array of fields that you want to return about the user. These properties correspond to the pieces of information that a user enters online about himself or herself in the Edit Profile pages. See Table 3-13 for a complete list of these fields. Table 3-13 User Elements Element Description Child Elements uid The user ID corresponding to the user info returned (always returned, even if unspecified) about_me Corresponds with About Me profile field activities Corresponds with user entered Activities profile field affiliations Network affiliations of user, year, type starting with the user’s [‘college”, primary network “high school”, “work”, “region”], status, name, and nid birthday User’s Birthday books User’s Favorite books current_ Current location city, state, country, location and zip education_ List of education_info education_info history elements children: name, year, and concentration first_name Generated from name in profile 88 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 88 Element Description Child Elements has_added_ Specifies whether user has app added the calling app (0 or 1) hometown_ Hometown profile fields city, state, country, location and zip hs_info High school information hs1_name, hs2_name, grad_year, hs1_key, and hs2_key interests Corresponds with Interests profile field is_app_user Specifies whether the user has ever used the calling app (0 or 1) last_name Generated from name in profile meeting_for List of desired relationships (blank, Friendship, A Relationship, Dating, Random Play, Whatever I can get) meeting_sex List of desired genders corresponding to the Interested In profile element movies Favorite movies music Favorite music name Name of user notes_count Total number of notes written by user pic URL of user profile picture (max. 100x300 px) pic_big URL of user profile picture (max. 200x600 px) pic_small URL of user profile picture (max. 50x150 px) pic_square URL of square picture (max. 50x50 px) (continued) Chapter 3: Working with the Facebook API 89 08_277959-ch03.qxp 5/5/08 11:26 AM Page 89 Table 3-13 (continued) Element Description Child Elements political Political view (blank, Very Liberal, Liberal, Moderate, Conservative, Very Conservative, Apathetic, Libertarian, Other) profile_ Time (in seconds since update_time epoch) that the user’s profile was last updated. 0 is returned if no recent updates have occurred. quotes Favorite quotes relationship_ Relationship status (blank, status Single, In a Relationship, In an Open Relationship, Engaged, Married, It’s Complicated) religion Religious views sex Sex significant_ User ID of the person the other_id user is in a relationship with status Status message message, time timezone Offset from GMT tv Favorite TV shows wall_count Total number of posts to the user’s wall work_history List of work_info location, company_ elements name, position, description, start_ date, and end_date In the following example, I use users_getInfo to retrieve basic details of the currently logged-in user and output them using print_r. I then apply that same logic to a more in-depth example by assigning the results to the 90 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 90 $user_details array. The data elements are then accessed from the array and output using echo. Here’s the code: users_getInfo”; echo “

”; echo “

Scenario 1: Get info on current user

”; $uid = $facebook->api_client->users_getLoggedInUser(); $desired_details = array(‘first_name’, ‘last_name’, ‘birthday’, ‘movies’, ‘pic’, ‘status’); $user_details = $facebook->api_client->users_getInfo($uid, $desired_details); echo “
Raw output:
”; echo “
”;
print_r($user_details);
echo “
”; echo “
Applied example:
”; $status = $user_details[0][‘status’][‘message’]; $first_name = $user_details[0][‘first_name’]; $last_name = $user_details[0][‘last_name’]; echo “$first_name $last_name $status
”; ?> The results are shown here: users_getInfo Scenario 1: Get info on current user Raw output: Array ( [0] => Array ( [uid] => 665127078 [first_name] => Rich [last_name] => Wagner [birthday] => [movies] => Casablanca, The Shawshank Redemption, It’s A Wonderful Life, Babette’s Feast, Field of Dreams, Pride & Prejudice (A&E Version), The Band of Brothers (HBO), Chariots of Fire, Amélie (Le Fabuleux destin d’Amélie Poulain), Groundhog Day, Braveheart, Princess Bride, Les Miserables (1998 version), Signs, The Lord of the Rings trilogy, Benny & Joon, Vertigo, Sense & Sensibility, The Count of Monte Cristo, A Little Princess, Double Indemnity, Forrest Gump, The Incredibles, The African Queen, Henry V (1989 version), The Truman Show Chapter 3: Work
$user_details array. The data elements are then accessed from the array and output using echo. Here’s the code: users_getInfo”; echo “

”; echo “

Scenario 1: Get info on current user

”; $uid = $facebook->api_client->users_getLoggedInUser(); $desired_details = array(‘first_name’, ‘last_name’, ‘birthday’, ‘movies’, ‘pic’, ‘status’); $user_details = $facebook->api_client->users_getInfo($uid, $desired_details); echo “
Raw output:
”; echo “
”;
print_r($user_details);
echo “
”; echo “
Applied example:
”; $status = $user_details[0][‘status’][‘message’]; $first_name = $user_details[0][‘first_name’]; $last_name = $user_details[0][‘last_name’]; echo “$first_name $last_name $status
”; ?> The results are shown here: users_getInfo Scenario 1: Get info on current user Raw output: Array ( [0] => Array ( [uid] => 665127078 [first_name] => Rich [last_name] => Wagner [birthday] => [movies] => Casablanca, The Shawshank Redemption, It’s A Wonderful Life, Babette’s Feast, Field of Dreams, Pride & Prejudice (A&E Version), The Band of Brothers (HBO), Chariots of Fire, Amélie (Le Fabuleux destin d’Amélie Poulain), Groundhog Day, Braveheart, Princess Bride, Les Miserables (1998 version), Signs, The Lord of the Rings trilogy, Benny & Joon, Vertigo, Sense & Sensibility, The Count of Monte Cristo, A Little Princess, Double Indemnity, Forrest Gump, The Incredibles, The African Queen, Henry V (1989 version), The Truman Show Chapter 3: Working with the Facebook API 91 08_277959-ch03.qxp 5/5/08 11:26 AM Page 91 [pic] => http://profile.ak.facebook.com/profile6/1237/103/ s665127078_3837.jpg ) ) Applied example: Rich Wagner says “bring on the Colts” A second example shows how to combine API calls to retrieve Facebook information. It shows how to use friends_get() and users_getInfo() to gather basic information on all the friends of the current user. The name and status message are displayed in a bulleted list. The code is as follows: Scenario 2: Get status of all friends of current user”; echo “
Applied example:
”; $friends = $facebook->api_client->friends_get(); $desired_details = array(‘last_name’,’first_name’, ‘status’); $friends_details = $facebook->api_client->users_getInfo($friends, $desired_details); echo “
    ”; if($friends_details){ foreach ($friends_details as $user_details) { $status = $user_details[‘status’][‘message’]; $first_name = $user_details[‘first_name’]; $last_name = $user_details[‘last_name’]; echo “
  • $first_name $last_name $status
  • ”; } } else { echo “
  • This user has no friends :(
  • ”; } echo “
”; ?> And it displays as this: Scenario 2: Get status of all friends of current user Applied example: Jared Wagner has a very tiny brain Justus Wagner solved immigration but then he forget how Jordan Wagner is chanting snow snow go away, come back on tuesday 92 Part II: Poking the API 08_277959-ch03.qxp 5/5/08 11:26 AM Page 92 Checking whether a user has your app with users.isAppAdded The users.isAppAdded determines whether the currently logged-in user has added the calling application. The syntax is as follows when using PHP: $facebook->api_client->users_isAppAdded() The method returns a 1 (true) or 0 (false). Checking permissions with users.hasAppPermissions Facebook requires that users grant special permission to an application to access certain parts of the API. The specific cases are setting a user’s status, uploading images to an album, and creating a listing. To allow users to opt in to these extended abilities, direct users to the following URL: www.facebook.com/authorize.php?api_key=YOUR_API_KEY&v=1.0&ext_perm=PERMISSION_ NAME The PERMISSION_NAME parameter can be status_update, photo_upload, or create_listing. Before performing one of these actions, you can check the extended permissions of a user using users.hasAppPermissions. Here is the syntax: $facebook->api_client->users_hasAppPermission($ext_perm) The $ext_perm parameter can be status_update, photo_upload, or create_listing. The result is a 1 (true) or 0 (false)

No comments