Guest

Adam Reineke

By: a guest on Dec 2nd, 2010  |  syntax: PHP  |  size: 4.62 KB  |  hits: 321  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. <?php
  2. # system\applicaton\libraries\Facebook.php
  3. if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  4.  
  5. class Facebook
  6. {
  7.         function Facebook()
  8.         {
  9.                
  10.         }
  11.        
  12.         function get_facebook_cookie()
  13.         {
  14.                 $args = array();
  15.                 parse_str(trim($_COOKIE['fbs_' . FACEBOOK_APP_ID], '\\"'), $args);
  16.                 ksort($args);
  17.                 $payload = '';
  18.                 foreach ($args as $key => $value)
  19.                 {
  20.                         if ($key != 'sig')
  21.                         {
  22.                                 $payload .= $key . '=' . $value;
  23.                         }
  24.                 }
  25.                 if (md5($payload . FACEBOOK_SECRET) != $args['sig'])
  26.                 {
  27.                         return null;
  28.                 }
  29.                 return $args;
  30.         }
  31. }
  32. ?>
  33.  
  34. <?php
  35. # system\application\helpers\header_helper.php
  36. function prepare_header($t)
  37. {
  38.         // Get the Facebook cookie
  39.         $cookie = $t->facebook->get_facebook_cookie();
  40.         if($cookie === NULL)
  41.                 return;
  42.        
  43.         // Get the decoded JSON object
  44.         $user = $t->user->get( $cookie['uid'] );
  45.         if($user == false)
  46.         {
  47.                 // The JSON wasn't found in the database, so get it from Facebook | TODO: Also fetch from FB is the data is too old.
  48.                 $json = $t->user->getJSON( $cookie['access_token'] );
  49.                 // Update user in database from JSON
  50.                 $t->user->update($json);
  51.                 // Get user from database | TODO: I believe we can save a DB call by just doing: $user = json_decode($json);
  52.                 $user = $t->user->get( $cookie['uid'] );
  53.         }
  54.         return $user;
  55. }
  56. ?>
  57.  
  58. <?php
  59. # system\application\config\Facebook.php
  60. if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  61. define('FACEBOOK_APP_ID', 'YOUR_APP_ID'); //TODO: Enter your app ID
  62. define('FACEBOOK_SECRET', 'YOUR_SECRET_KEY'); //TODO: Enter your secret key
  63. ?>
  64.  
  65. <?php
  66. # system\application\models\user.php
  67. class User extends Model
  68. {
  69.         function User()
  70.         {
  71.                 parent::Model();
  72.         }
  73.        
  74.         /**
  75.          * Gets the JSON file string for the logged in user with the access token [from the cookie].
  76.          * See http://developers.facebook.com/docs/api for more info on the Graph API.
  77.          */
  78.         function getJSON($access_token)
  79.         {
  80.                 if($access_token == "")
  81.                 {
  82.                         throw new Exception("Access token may not be blank."); // TODO: Figure out causes. Did you clear your cookies?
  83.                 }
  84.                 return file_get_contents('https://graph.facebook.com/me?access_token=' . $access_token);
  85.         }
  86.        
  87.         /**
  88.          * Given the JSON, updates the user in database. If the user does not exist, the user is added.
  89.          */
  90.         function update($json)
  91.         {
  92.                 $decoded = json_decode($json); // object
  93.                 if($decoded === NULL)
  94.                 {
  95.                         throw new Exception("Error decoding JSON file. Last error: " . json_last_error() . "\n" . $json);
  96.                 }
  97.                
  98.                 $this->db->where('uid', $decoded->id);
  99.                 $query = $this->db->get('users');
  100.                 if($query->num_rows() == 0)
  101.                 {
  102.                         $data = array(
  103.                                 'uid' => $decoded->id,
  104.                                 'name' => $decoded->name,
  105.                                 'json' => $json
  106.                         );
  107.                         $this->db->insert('users', $data);
  108.                 }
  109.                 else
  110.                 {
  111.                         $this->db->where('uid', $decoded->id);
  112.                         $this->db->update('users', $data);     
  113.                 }
  114.         }
  115.        
  116.         /**
  117.          * Gets the stored JSON from the database and returns it as a decoded object.
  118.          */
  119.         function get($uid)
  120.         {
  121.                 $this->db->where('uid', $uid);
  122.                 $query = $this->db->get('users');
  123.                 if($query->num_rows() == 0)
  124.                 {
  125.                         return false;
  126.                 }
  127.                 else
  128.                 {
  129.                         return json_decode($query->row()->json);
  130.                 }
  131.         }
  132.        
  133.         /**
  134.          * Gets the user role
  135.          */
  136.          function get_role($uid)
  137.          {
  138.                 $this->db->where('uid', $uid);
  139.                 $query = $this->db->get('users');
  140.                 if($query->num_rows() == 0)
  141.                         return false;
  142.                 else
  143.                         return $query->row()->role;
  144.          }
  145.  
  146. }
  147. ?>
  148.  
  149. <!-- system\application\views\_header.php -->
  150. <!-- Header for every page -->
  151. <?php
  152. /*
  153.  * This expects a user parameter (decoded JSON)
  154.  */
  155. ?>
  156. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  157. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
  158. <head>
  159.         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  160.         <title>Your Site</title>
  161. </head>
  162.  
  163. <body>
  164. <div class="container">
  165.                         <div id="fb-root"></div>
  166.                         <script src="http://connect.facebook.net/en_US/all.js"></script>
  167.                         <script>
  168.                           FB.init({appId: '<?= FACEBOOK_APP_ID ?>', status: true,
  169.                                            cookie: true, xfbml: true});
  170.                           FB.Event.subscribe('auth.login', function(response) {
  171.                                 window.location.reload();
  172.                           });
  173.                         </script>
  174.                         <?php
  175.                                 if ($id) {
  176.                                         echo '<p>Welcome ' . $name . '</p>';
  177.                        
  178.                                 } else { ?>
  179.                                   <fb:login-button></fb:login-button>
  180.                         <?php } ?>
  181. <!-- Your footer would close out these divs. You can figure that out. -->
  182.  
  183. <?php
  184. /* MySQL for the user table.
  185.  
  186. CREATE TABLE IF NOT EXISTS `users` (
  187.   `uid` int(11) NOT NULL,
  188.   `name` varchar(100) NOT NULL,
  189.   `json` text NOT NULL,
  190.   PRIMARY KEY  (`uid`)
  191. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  192. */