From 2080b3617c6b0948e596a8a9585b9a634cbea59b Mon Sep 17 00:00:00 2001
From: mcaden <mcaden@gmail.com>
Date: Mon, 21 Mar 2011 14:58:24 -0700
Subject: [PATCH] fb-[#1022932]

---
 fb.js         |   63 +++++++++++++++++++++++++++++++++++++-------------------
 fb.module     |   43 ++++++++++++++++++++++----------------
 fb_connect.js |    5 +++-
 3 files changed, 70 insertions(+), 41 deletions(-)

diff --git a/fb.js b/fb.js
index 907fbd4..2ee4a23 100644
--- a/fb.js
+++ b/fb.js
@@ -146,6 +146,7 @@ FB_JS.sessionChange = function(response) {
 
     // 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.
+    FB_JS.deleteCookie('fbs_' + FB._apiKey, '/', '');
     FB_JS.deleteCookie('fbs_' + Drupal.settings.fb.apikey, '/', '');
   }
 
@@ -189,41 +190,59 @@ FB_JS.sessionChangeHandler = function(context, status) {
 
 // Helper to pass events via AJAX.
 // A list of javascript functions to be evaluated is returned.
-FB_JS.ajaxEvent = function(event_type, data) {
+FB_JS.ajaxEvent = function(event_type, request_data) {
   if (Drupal.settings.fb.ajax_event_url) {
 
     // Session data helpful in ajax callbacks.  See fb_settings.inc.
-    data.fb_js_session = JSON.stringify(FB.getSession());
+    request_data.fb_js_session = JSON.stringify(FB.getSession());
     if (typeof(Drupal.settings.fb_page_type) != 'undefined') {
-      data.fb_js_page_type = Drupal.settings.fb_page_type;
+      request_data.fb_js_page_type = Drupal.settings.fb_page_type;
     }
 
     // Other values to always include.
-    data.apikey = FB._apiKey;
+    // FB._apikey might be an apikey or might be an appid!
+    if (FB._apiKey == Drupal.settings.fb.fb_init_settings.appId ||
+        FB._apiKey == Drupal.settings.fb.fb_init_settings.apiKey) {
+      request_data.apikey = Drupal.settings.fb.fb_init_settings.apiKey;
+    }
+
+    // Other values to pass to ajax handler.
     if (Drupal.settings.fb.controls) {
-      data.fb_controls = Drupal.settings.fb.controls;
+      request_data.fb_controls = Drupal.settings.fb.controls;
     }
 
-    jQuery.post(Drupal.settings.fb.ajax_event_url + '/' + event_type, data,
-	        function(js_array, textStatus, XMLHttpRequest) {
-	          //debugger; // debug
-	          if (js_array.length > 0) {
-	            for (var i = 0; i < js_array.length; i++) {
-	              eval(js_array[i]);
-	            }
-	          }
-	          else {
-	            if (event_type == 'session_change') {
-	              // No instructions from ajax, reload entire page.
-	              FB_JS.reload();
-	            }
-	          }
-	        }, 'json');
+    jQuery.ajax({
+      url: Drupal.settings.fb.ajax_event_url + '/' + event_type,
+      data : request_data,
+      type: 'POST',
+      dataType: 'json',
+      success: function(js_array, textStatus, XMLHttpRequest) {
+        if (js_array.length > 0) {
+          for (var i = 0; i < js_array.length; i++) {
+            eval(js_array[i]);
+          }
+        }
+        else {
+          if (event_type == 'session_change') {
+            // No instructions from ajax, reload entire page.
+            FB_JS.reload();
+          }
+        }
+      },
+      error: function(jqXHR, textStatus, errorThrown) {
+        var header = jqXHR.getResponseHeader();
+        var headers = jqXHR.getAllResponseHeaders();
+        debugger;
+        // @TODO: handle error, but how?
+        FB_JS.reload();
+        //alert('FB_JS.ajaxEvent error handler called.');
+      }
+    });
   }
 };
 
 // Delete a cookie.
-// ??? Still needed?  Facebook's JS SDK may take care of this now.
+// Facebook's JS SDK attempts to delete, but I'm not convinced it always works.
 FB_JS.deleteCookie = function( name, path, domain ) {
   document.cookie = name + "=" +
     ( ( path ) ? ";path=" + path : "") +
@@ -255,7 +274,7 @@ FB_JS.sessionSanityCheck = function() {
 	jQuery(document).bind('fb_session_change', FB_JS.sessionChangeHandler);
       }
 
-      // Once upon a time, we initialized facebook's JS SDK here.  But now that is done in fb_footer().
+      // Once upon a time, we initialized facebook's JS SDK here, but now that is done in fb_footer().
 
       if (typeof(FB) != 'undefined') {
         // Render any XFBML markup that may have been added by AJAX.
diff --git a/fb.module b/fb.module
index edcf34a..e4042ea 100644
--- a/fb.module
+++ b/fb.module
@@ -368,7 +368,7 @@ function fb_api_init($fb_app) {
 
     // We don't have a cached resource for this app, so we're going to create one.
     $fb = new Facebook(array(
-                         'appId' => $fb_app->apikey,
+                         'appId' => $fb_app->id,
                          'secret' => isset($fb_app->secret) ? $fb_app->secret : NULL,
                          'cookie' => variable_get(FB_VAR_USE_COOKIE, TRUE),
                        ));
@@ -712,7 +712,7 @@ function fb_api_check_session($fb) {
   catch (Exception $e) {
     if (fb_verbose()) {
       watchdog('fb', 'fb_api_check_session failed. Possible attempt to spoof a facebook session!');
-      watchdog('fb', print_r($fb->getSession(), 1));
+      // watchdog('fb', print_r($fb->getSession(), 1));
     }
     $success = FALSE;
     if (fb_verbose()) {
@@ -744,9 +744,14 @@ function _fb_logout() {
   // Unsetting the javasript fbu can be helpful when third-party cookies disabled.
   fb_js_settings('fbu', 0);
 
-  // Clean up facebook cookies.  We may need this when third-party cookies disabled.
-  if (isset($GLOBALS['_fb_app']) && isset($_COOKIE['fbs_' . $GLOBALS['_fb_app']->apikey])) {
-    setcookie('fbs_' . $GLOBALS['_fb_app']->apikey, '', time() - 42000, '/');
+  // Clean up facebook cookies.
+  if (isset($GLOBALS['_fb_app'])) {
+    if (isset($_COOKIE['fbs_' . $GLOBALS['_fb_app']->apikey])) {
+      setcookie('fbs_' . $GLOBALS['_fb_app']->apikey, '', time() - 42000, '/');
+    }
+    if (isset($_COOKIE['fbs_' . $GLOBALS['_fb_app']->id])) {
+      setcookie('fbs_' . $GLOBALS['_fb_app']->id, '', time() - 42000, '/');
+    }
   }
 }
 
@@ -1499,26 +1504,28 @@ function fb_ajax_event($event_type) {
 
       $js_array = fb_invoke(FB_OP_AJAX_EVENT, $data, array());
 
-      if ($event_type == 'session_change') {
-        // Session change is a special case.  If user has logged out of
-        // facebook, we want a new drupal session.  We do this here, even if
-        // fb_user.module is not enabled.
-        if (!$_POST['fbu'] && isset($_SESSION['fb'][$_fb_app->apikey])) {
-          _fb_logout();
-        }
+    }
+    else {
+      watchdog('fb', 'fb_ajax_event did not find application %id', array('%id' => $_REQUEST['apikey']), WATCHDOG_ERROR);
+    }
+ 
+    if ($event_type == 'session_change') {
+      // Session change is a special case.  If user has logged out of
+      // facebook, we want a new drupal session.  We do this here, even if
+      // fb_user.module is not enabled.
+      if (!isset($_POST['fbu']) || !$_POST['fbu']) { // Logout, not login.
+        _fb_logout();
       }
-
     }
   }
   else {
+    watchdog('fb', 'fb_ajax_event called badly.  Not passed apikey.', array(), WATCHDOG_ERROR);
     // Trying to track down what makes this happen.
     if (fb_verbose() == 'extreme') {
-      $js_array[] = 'alert("fb_ajax_event called badly.  Not passed apikey.");'; // debug
+      watchdog('fb', 'fb_ajax_event called badly.  Not passed apikey. trace: !trace', array(
+                 '!trace' => '<pre>' . print_r(debug_backtrace(), 1) . '</pre>',
+               ), WATCHDOG_ERROR);
     }
-    watchdog('fb', 'fb_ajax_event called badly. Not passed apikey.', array(), WATCHDOG_ERROR);
-    watchdog('fb', 'fb_ajax_event called badly.  Not passed apikey. trace: !trace', array(
-               '!trace' => '<pre>' . print_r(debug_backtrace(), 1) . '</pre>',
-             ), WATCHDOG_ERROR);
   }
   drupal_json_output($js_array);
   exit();
diff --git a/fb_connect.js b/fb_connect.js
index 8d45eac..7a22724 100644
--- a/fb_connect.js
+++ b/fb_connect.js
@@ -51,8 +51,11 @@ FB_Connect.sessionChangeHandler = function(context, status) {
 FB_Connect.logoutHandler = function(event) {
   if (typeof(FB) != 'undefined') {
     FB.logout(function () {
-      //debugger;
     });
+    // Facebook's invalid cookies persist if third-party cookies disabled.
+    // 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
   }
 };
 
-- 
1.7.4.msysgit.0

