Index: fb_devel.module
===================================================================
--- fb_devel.module	(revision 3789)
+++ fb_devel.module	(working copy)
@@ -316,19 +316,22 @@
   global $user;
 
   if (isset($_REQUEST['require_login']) && $_REQUEST['require_login'])
-    $_fb->require_login();  // @TODO - find a way to do this with new api.
+    $_fb->require_login();
 
   if ($_fb) {
     // TODO: determine whether connect page or canvas.
 
     drupal_set_message(t("session name: " . session_name()));
+    drupal_set_message(t("session id: " . session_id()));
     drupal_set_message(t("cookie domain: " . fb_settings(FB_SETTINGS_COOKIE_DOMAIN)));
-    drupal_set_message(t("session id: " . session_id()));
+
     if (isset($_COOKIE['fbs_' . $_fb_app->apikey]))
       drupal_set_message(t("fbs_" . $_fb_app->apikey . ": " . $_COOKIE["fbs_" . $_fb_app->apikey]));
     drupal_set_message(t("<a href=\"!url\">processed link</a>, <a href=!url>unprocessed</a>", array('!url' => url('fb/devel'))));
     drupal_set_message(t("getUser() returns " . $_fb->getUser()));
 
+    drupal_set_message(t("getAccessToken() returns " . $_fb->getAccessToken()));
+
     drupal_set_message(t("base_url: " . $GLOBALS['base_url']));
     drupal_set_message(t("base_path: " . $GLOBALS['base_path']));
     drupal_set_message(t("url() returns: " . url()));
@@ -351,7 +354,6 @@
   dpm($_COOKIE, 'cookie');
   dpm($_REQUEST, "Request");
   //dpm($_fb_app, "fb_app");
-  drupal_set_message(t("session_id returns " . session_id()));
   dpm($_SESSION, "session:");
 
   return "This is the facebook debug page.";
@@ -426,8 +428,15 @@
 function fb_devel_fbu_page($fbu = NULL) {
   global $_fb, $_fb_app;
   if ($fbu) {
+    // Uses FQL
+    $info = fb_users_getInfo(array($fbu), $_fb);
+    $output = "<p>Debug FQL info about facebook id $fbu ({$info[0]['name']}):</p>\n";
+    $output .= "<img src=http://graph.facebook.com/$fbu/picture></img>";
+    $output .= "<pre>" . print_r($info[0], 1) . "</pre>";
+
+    // Use new graph api
     $info = $_fb->api($fbu, array('metadata' => 1));
-    $output = "<p>Debug info about facebook id $fbu ({$info[name]}):</p>\n";
+    $output .= "<p>Debug info about facebook id $fbu ({$info['name']}):</p>\n";
     $output .= "<img src=http://graph.facebook.com/$fbu/picture></img>";
     $output .= "<pre>" . print_r($info, 1) . "</pre>";
 
@@ -448,7 +457,7 @@
       //dpm($friends, "$fbu/friends returned");
       $items = array();
       foreach ($friends['data'] as $data) {
-        $items[] = l($data['name'], "fb/devel/fbu/{$data[id]}");
+        $items[] = l($data['name'], "fb/devel/fbu/{$data['id']}");
       }
       if (count($items)) {
         $output .= "\n<p>Known friends:<ul><li>";
@@ -604,7 +613,7 @@
     catch (FacebookApiException $e) {
       fb_log_exception($e, "failed to get app properties");
     }
-    $info["fb->getSession()"] = $_fb->getSession();
+   // $info["fb->getSession()"] = $_fb->getSession();
     $info["fb->getSignedRequest()"] = $_fb->getSignedRequest();
     if ($fbu) {
       try {
Index: fb.js
===================================================================
--- fb.js	(revision 3789)
+++ fb.js	(working copy)
@@ -27,10 +27,14 @@
  * Finish initializing, whether there is an application or not.
  */
 FB_JS.initFinal = function(response) {
-  var status = {'session' : response.session, 'response': response};
+  var status = {
+    'session' : response.authResponse, // deprecated
+    'auth': response.authResponse,
+    'response': response
+  };
   jQuery.event.trigger('fb_init', status);  // Trigger event for third-party modules.
 
-  FB_JS.sessionChange(response); // This will act only if fbu changed.
+  FB_JS.authResponseChange(response); // This will act only if fbu changed.
 
   FB_JS.eventSubscribe();
 
@@ -42,7 +46,7 @@
  */
 FB_JS.eventSubscribe = function() {
   // Use FB.Event to detect Connect login/logout.
-  FB.Event.subscribe('auth.sessionChange', FB_JS.sessionChange);
+  FB.Event.subscribe('auth.authResponseChange', FB_JS.authResponseChange);
 
   // Q: what the heck is "edge.create"? A: the like button was clicked.
   FB.Event.subscribe('edge.create', FB_JS.edgeCreate);
@@ -75,10 +79,11 @@
  */
 FB_JS.reload = function(destination) {
   // Determine url hash.
-  var session = FB.getSession();
+  var auth = FB.getAuthResponse();
+
   var fbhash;
-  if (session != null)
-    fbhash = session.sig; // Use sig rather than compute a new hash.
+  if (auth != null)
+    fbhash = auth.signedRequest; // Use sig rather than compute a new hash.
   else
     fbhash = 0;
 
@@ -132,15 +137,22 @@
 };
 
 // Facebook pseudo-event handlers.
-FB_JS.sessionChange = function(response) {
+FB_JS.authResponseChange = function(response) {
+  //debugger;
   if (response.status == 'unknown') {
     // @TODO can we test if third-party cookies are disabled?
   }
 
-  var status = {'changed': false, 'fbu': null, 'session': response.session, 'response' : response};
+  var status = {
+    'changed': false,
+    'fbu': null,
+    'session': response.authResponse, // deprecated,  still needed???
+    'auth': response.authResponse, // still needed???
+    'response' : response
+  };
 
-  if (response.session) {
-    status.fbu = response.session.uid;
+  if (response.authResponse) {
+    status.fbu = response.authResponse.userID;
     if (Drupal.settings.fb.fbu != status.fbu) {
       // A user has logged in.
       status.changed = true;
@@ -152,6 +164,7 @@
 
     // Sometimes Facebook's invalid cookies are left around.  Let's try to clean up their crap.
     // Can get left behind when third-party cookies disabled.
+    // Still needed with new oauth???
     FB_JS.deleteCookie('fbs_' + FB._apiKey, '/', '');
     FB_JS.deleteCookie('fbs_' + Drupal.settings.fb.apikey, '/', '');
   }
@@ -180,7 +193,7 @@
   };
 
   if (status.session) {
-    data.fbu = status.session.uid;
+    data.fbu = status.session.userID;
     // Suppress facebook-controlled session.
     data.fb_session_handoff = true;
   }
@@ -196,7 +209,7 @@
   if (Drupal.settings.fb.ajax_event_url) {
 
     // Session data helpful in ajax callbacks.  See fb_settings.inc.
-    request_data.fb_js_session = JSON.stringify(FB.getSession());
+    // request_data.fb_js_session = JSON.stringify(FB.getSession()); // FB.getSession() FAILS! REMOVE or REPLACE.
     if (typeof(Drupal.settings.fb_page_type) != 'undefined') {
       request_data.fb_js_page_type = Drupal.settings.fb_page_type;
     }
Index: fb.module
===================================================================
--- fb.module	(revision 3789)
+++ fb.module	(working copy)
@@ -147,6 +147,7 @@
     'xfbml' => FALSE,
     'status' => FALSE,
     'cookie' => variable_get(FB_VAR_USE_COOKIE, TRUE),
+    'oauth' => TRUE,
   );
 
   // Figure out which app the current request is for.
@@ -167,43 +168,11 @@
 
     if ($_fb) {
 
-      // Look for session info from several sources.
-      if ($session = $_fb->getSession()) {
-        // Learned session from cookie or signed request.
-        // Below, we store in our $_SESSION, just in case third-party cookies are not enabled.
-      }
-      elseif (isset($_REQUEST['fb_js_session'])) {
-        // Ajax callback via fb.js.
-        $_fb->setSession(json_decode($_REQUEST['fb_js_session'], TRUE));
-        $session = $_fb->getSession();
-      }
-      elseif (isset($_SESSION['fb'][$_fb_app->id]['session']) && arg(0) != 'logout') {
-        // Use the session previously stored.
-        $_fb->setSession($_SESSION['fb'][$_fb_app->id]['session']);
-      }
+      // @TODO: test this code with third party cookies disabled.
 
-      // Store session for future use.  We'll need it if third-party cookies
-      // disabled, or we are not using facebook's cookie.
-      if (isset($session) && variable_get(FB_VAR_USE_SESSION, TRUE)) {
-        $_SESSION['fb'][$_fb_app->id]['session'] = $session;
-      }
-
-      // Make javascript work even when third-party cookies disabled.
-      $fb_init_settings['session'] = $_fb->getSession();
-
-      // Sometimes when canvas page is open in one tab, and user logs out of
+      // @TODO: test if this is still true: Sometimes when canvas page is open in one tab, and user logs out of
       // facebook in another, the canvas page has bogus session info when
       // refreshed.  Here we attempt to detect and cleanup.
-      if (isset($session) && ($request = $_fb->getSignedRequest())) {
-        if (!isset($request['user_id']) ||
-            $request['user_id'] != $session['uid']) {
-          _fb_logout();
-          $_fb->setSession(NULL);
-          unset($session);
-          unset($_SESSION['fb'][$_fb_app->id]);
-          unset($fb_init_settings['session']);
-        }
-      }
 
       // Give other modules a chance to initialize.
       fb_invoke(FB_OP_INITIALIZE, array(
@@ -212,13 +181,13 @@
                 ));
 
       // See if the facebook user id is known
-      if ($fbs = $_fb->getSession()) {
+      if ($fbu = $_fb->getUser()) {
         fb_invoke(FB_OP_APP_IS_AUTHORIZED, array(
                     'fb_app' => $_fb_app,
                     'fb' => $_fb,
-                    'fbu' => $_fb->getUser(),
+                    'fbu' => $fbu,
                   ));
-        fb_js_settings('fbu', $_fb->getUser());
+        fb_js_settings('fbu', $fbu);
       }
       else {
         // Add perms to settings, for calling FB.login().
@@ -356,8 +325,8 @@
       return NULL;
     }
 
-    if (Facebook::VERSION >= "3") {
-      $message = 'This version of modules/fb is compatible with Facebook PHP SDK version 2.x, but %version was found.  Either upgrade modules/fb or downgrade %fb_platform.';
+    if (Facebook::VERSION < "3") {
+      $message = 'This version of modules/fb is compatible with Facebook PHP SDK version 3.x.y, but %version was found (%fb_platform).';
       $args = array('%fb_platform' => $fb_platform, '%version' => Facebook::VERSION);
       if (user_access('access administration pages')) {
         drupal_set_message(t($message, $args));
@@ -470,8 +439,7 @@
     $cache_key .= '_' . $fbu;
     // Get the user access token.
     if ($fbu == 'me' || $fbu == fb_facebook_user($fb)) {
-      $session = $fb->getSession();
-      $cache[$cache_key] = $session['access_token'];
+      $cache[$cache_key] = $fb->getAccessToken();
     }
     else {
       $session_data = fb_invoke(FB_OP_GET_USER_SESSION, array(
@@ -699,7 +667,7 @@
 
     unset($_SESSION['fb'][$fb->getAppId()]);
     // Unsetting the javasript fbu can be helpful when third-party cookies disabled.
-    fb_js_settings('fbu', 0);
+    //fb_js_settings('fbu', 0); @TODO still needed? helpful?
 
     // Might as well try to clean up the mess.
     if (isset($_COOKIE['fbs_' . $fb->getAppId()])) {
@@ -721,7 +689,7 @@
   $GLOBALS['user'] = drupal_anonymous_user();
 
   // Unsetting the javasript fbu can be helpful when third-party cookies disabled.
-  fb_js_settings('fbu', 0);
+  //fb_js_settings('fbu', 0); @TODO still needed?? helpful???
 
   // Clean up facebook cookies.
   if (isset($GLOBALS['_fb_app'])) {
Index: fb_connect.js
===================================================================
--- fb_connect.js	(revision 3789)
+++ fb_connect.js	(working copy)
@@ -57,12 +57,12 @@
     // Let's try to clean up the mess.
     FB_JS.deleteCookie('fbs_' + FB._apiKey, '/', ''); // app id
     FB_JS.deleteCookie('fbs_' + Drupal.settings.fb.apikey, '/', ''); // apikey
-  }
-  if (FB.getSession()) {
+  }/*
+  if (FB.getSession()) { // FB.getSession() FAILS! REMOVE or REPLACE.
     // Facebook needs more time to log us out. (http://drupal.org/node/1164048)
     Drupal.settings.fb.reload_url = Drupal.settings.fb_connect.front_url;
     return false;
-  }
+  }*/
 };
 
 /**
Index: fb_settings.inc
===================================================================
--- fb_settings.inc	(revision 3789)
+++ fb_settings.inc	(working copy)
@@ -217,6 +217,8 @@
   }
 }
 elseif (isset($_REQUEST['fb_js_session'])) {
+  // @TODO: Still need this clause with new oauth SDK???
+
   // Ajax callback via fb.js.
   $session = json_decode($_REQUEST['fb_js_session'], TRUE);
   fb_settings(FB_SETTINGS_TYPE, isset($_REQUEST['fb_js_page_type']) ? $_REQUEST['fb_js_page_type'] : FB_SETTINGS_TYPE_CONNECT);
Index: fb_connect.module
===================================================================
--- fb_connect.module	(revision 3789)
+++ fb_connect.module	(working copy)
@@ -150,7 +150,7 @@
       // @TODO fb.module should have a helper to make this cleaner.
 
       $settings['fb_init_settings']['appId'] = $fb_app->id;
-      $settings['fb_init_settings']['session'] = $fb->getSession();
+      //$settings['fb_init_settings']['session'] = $fb->getSession();
       fb_js_settings('apikey', $fb_app->apikey);
       fb_js_settings('fbu', fb_facebook_user($fb));
       fb_js_settings('fb_init_settings', $settings['fb_init_settings']);
@@ -168,11 +168,11 @@
 function _fb_connect_block_login_defaults() {
   return array('anon_not_connected' => array(
                  'title' => t('Facebook Connect'),
-                 'body' => '<fb:login-button perms="!perms" v="2">Connect</fb:login-button>',
+                 'body' => '<fb:login-button scope="!perms" v="2">Connect</fb:login-button>',
                ),
                'user_not_connected' => array(
                  'title' => t('Facebook Connect'),
-                 'body' => '<fb:login-button perms="!perms" v="2">Connect</fb:login-button>',
+                 'body' => '<fb:login-button scope="!perms" v="2">Connect</fb:login-button>',
                ),
                'connected' => array(
                  'title' => t('Facebook Connect'),
Index: fb.install
===================================================================
--- fb.install	(revision 3789)
+++ fb.install	(working copy)
@@ -63,12 +63,12 @@
 
   if (class_exists('Facebook')) {
     $status['value'] = Facebook::VERSION;
-    if (Facebook::VERSION >= "3") {
-      $status['description'] = $t('Expected version 2.x.y of Facebook PHP SDK.');
+    if (Facebook::VERSION < "3" || Facebook::VERSION > "4") {
+      $status['description'] = $t('Expected version 3.x.y of Facebook PHP SDK.');
       $status['severity'] = REQUIREMENT_ERROR;
     }
     else {
-      $status['description'] = $t('Facebook PHP SDK loaded.');
+      $status['description'] = $fb_platform;
       $status['severity'] = REQUIREMENT_OK;
     }
   }
Index: contrib/fb_user_app.module
===================================================================
--- contrib/fb_user_app.module	(revision 3789)
+++ contrib/fb_user_app.module	(working copy)
@@ -71,7 +71,7 @@
       $fbu = fb_settings(FB_SETTINGS_FBU);
       // User has removed the app from their account.
       db_query("DELETE FROM {fb_user_app} WHERE apikey='%s' AND fbu=%d",
-        $fb_app->apikey, $fbu);
+               $fb_app->apikey, $fbu);
     }
   }
   elseif ($op == FB_OP_GET_USER_SESSION) {
@@ -121,8 +121,13 @@
  * Keep track of when the user has visited the app, and whether they've
  * authorized the app or not.
  *
- * Historically this supported infinite sessions.  I believe if this data is
- * no longer necessary for the offline access extended permission.
+ * Historically, we could update rows in fb_user_app each time a user visited
+ * a page.  With recent changes to faceobok platform, it is unclear exactly
+ * when all the necessary data is available.  On a typical page request, the
+ * "signed request" contains little that is useful, while during an authorized
+ * callback, it contains an access token and expires data.  So the code below
+ * has become conservative, writing to fb_user_app only when the information
+ * seems reliable.
  */
 function fb_user_app_track_user($fb, $fb_app) {
   // Coming from a user adding the app or a page adding the app?
@@ -134,35 +139,44 @@
     $fbu = $_REQUEST['fb_sig_page_id'];
   }
 
+  $sr = $fb->getSignedRequest();
+  watchdog('fb_user_app', __FUNCTION__ . " signed request is <pre>" . print_r($sr,1) . "</pre>"); // debug
 
-  // test if we are tracking only those apps that have been granted offline
-  // access.
-  $fb_session = $fb->getSession();
+  if (isset($sr['oauth_token'])) {
+    $access_token = $sr['oauth_token'];
+    $expires = $sr['expires'];
+    $fbu = $sr['user_id'];
+  }
+  else {
+    // @TODO: with new SDK, is there any useful tracking info?
+    return;
+  }
 
+
   // when 'expires' == 0 app has been granted offline access
   if ($fb_user_type == 'user' &&
       $fb_session["expires"] <> 0 &&
-      variable_get(FB_USER_APP_VAR_USERS_THAT_GRANT_OFFLINE, FALSE))
+      variable_get(FB_USER_APP_VAR_USERS_THAT_GRANT_OFFLINE, FALSE)) {
+    // Note, with new SDK, facebook provides 'expires' date even when user HAS GRANTED offline_access!
+    // @TODO: find some way to tell whether an access token will actually expire!
     return;
+  }
 
   // Track this event only if allowed to and only for users, not pages
   if ((variable_get(FB_USER_APP_VAR_TRACK_USERS, TRUE) && $fb_user_type = "user") ||
       (variable_get(FB_USER_APP_VAR_TRACK_PAGES, TRUE) && $fb_user_type = "page")) {
 
-    $session = $fb->getSession();
-    // Session key no longer useful, now store access token.
-    $access_token = isset($session['access_token']) ? $session['access_token'] : '';
     $result = db_query("UPDATE {fb_user_app} SET time_access=%d, session_key='%s', session_key_expires=%d, user_type='%s' WHERE apikey='%s' AND fbu=%d",
                        time(),
-                       $access_token, $session['expires'],
+                       $access_token, $expires,
                        $fb_user_type,
-                       $fb_app->apikey, fb_facebook_user($fb));
+                       $fb_app->id,
+                       $fbu);
 
     if ($result && !db_affected_rows()) {
       // The row for this user was never inserted, or it was deleted, or the times were the same.
-      $fbu = fb_facebook_user($fb);
       if ($fbu) {
-        //First make sure it was not just the same time
+        // First make sure it was not just the same time
         $result = db_query("SELECT * FROM {fb_user_app} WHERE apikey='%s' AND fbu=%d",
                            $fb_app->apikey,
                            $fbu);
@@ -176,7 +190,7 @@
                              $data['is_app_user'],
                              $fb_user_type,
                              $access_token,
-                             $session['expires'],
+                             $expires,
                              time(),
                              $data['proxied_email'],
                              0 // time_cron
