]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - plugins/FacebookBridge/FacebookBridgePlugin.php
Added more checked type-hints.
[quix0rs-gnu-social.git] / plugins / FacebookBridge / FacebookBridgePlugin.php
index d5a3f7c633f27a6650d8c183dbcd205775fd1420..83170396d2f77a1d2df8c6b13221fa348426746b 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /**
  * StatusNet - the distributed open-source microblogging tool
- * Copyright (C) 2010, StatusNet, Inc.
+ * Copyright (C) 2010-2011, StatusNet, Inc.
  *
  * A plugin for integrating Facebook with StatusNet. Includes single-sign-on
  * and publishing notices to Facebook using Facebook's Graph API.
@@ -21,7 +21,7 @@
  * You should have received a copy of the GNU Affero General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
- * @category  Pugin
+ * @category  Plugin
  * @package   StatusNet
  * @author    Zach Copley <zach@status.net>
  * @copyright 2011 StatusNet, Inc.
@@ -41,7 +41,7 @@ define("FACEBOOK_SERVICE", 2);
  * @category  Plugin
  * @package   StatusNet
  * @author    Zach Copley <zach@status.net>
- * @copyright 2010 StatusNet, Inc.
+ * @copyright 2010-2011 StatusNet, Inc.
  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  * @link      http://status.net/
  */
@@ -101,34 +101,17 @@ class FacebookBridgePlugin extends Plugin
      */
     function onAutoload($cls)
     {
-
         $dir = dirname(__FILE__);
 
-        //common_debug("class = " . $cls);
-
         switch ($cls)
         {
         case 'Facebook': // Facebook PHP SDK
+            include_once $dir . '/extlib/base_facebook.php';
             include_once $dir . '/extlib/facebook.php';
             return false;
-        case 'FacebookloginAction':
-        case 'FacebookfinishloginAction':
-        case 'FacebookadminpanelAction':
-        case 'FacebooksettingsAction':
-        case 'FacebookdeauthorizeAction':
-            include_once $dir . '/actions/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
-            return false;
-        case 'Facebookclient':
-        case 'FacebookQueueHandler':
-            include_once $dir . '/lib/' . strtolower($cls) . '.php';
-            return false;
-        case 'Notice_to_item':
-            include_once $dir . '/classes/' . $cls . '.php';
-            return false;
-        default:
-            return true;
         }
 
+        return parent::onAutoload($cls);
     }
 
     /**
@@ -170,11 +153,11 @@ class FacebookBridgePlugin extends Plugin
     /**
      * Map URLs to actions
      *
-     * @param Net_URL_Mapper $m path-to-action mapper
+     * @param URLMapper $m path-to-action mapper
      *
      * @return boolean hook value; true means continue processing, false means stop.
      */
-    function onRouterInitialized($m)
+    public function onRouterInitialized(URLMapper $m)
     {
         // Always add the admin panel route
         $m->connect('panel/facebook', array('action' => 'facebookadminpanel'));
@@ -214,10 +197,11 @@ class FacebookBridgePlugin extends Plugin
         if ($this->hasApplication()) {
 
             $action->menuItem(
+                // TRANS: Menu item for "Facebook" login.
                 common_local_url('facebooklogin'),
                 _m('MENU', 'Facebook'),
-                // TRANS: Tooltip for menu item "Facebook".
-                _m('Login or register using Facebook'),
+                // TRANS: Menu title for "Facebook" login.
+                _m('Login or register using Facebook.'),
                'facebooklogin' === $action_name
             );
         }
@@ -245,7 +229,7 @@ class FacebookBridgePlugin extends Plugin
      *
      * @return boolean hook value
      */
-    function onEndAdminPanelNav($nav)
+    function onEndAdminPanelNav(Menu $nav)
     {
         if (AdminPanelAction::canAdmin('facebook')) {
 
@@ -253,10 +237,10 @@ class FacebookBridgePlugin extends Plugin
 
             $nav->out->menuItem(
                 common_local_url('facebookadminpanel'),
-                // TRANS: Menu item.
+                // TRANS: Menu item for "Facebook" in administration panel.
                 _m('MENU','Facebook'),
-                // TRANS: Tooltip for menu item "Facebook".
-                _m('Facebook integration configuration'),
+                // TRANS: Menu title for "Facebook" in administration panel.
+                _m('Facebook integration configuration.'),
                 $action_name == 'facebookadminpanel',
                 'nav_facebook_admin_panel'
             );
@@ -278,8 +262,7 @@ class FacebookBridgePlugin extends Plugin
         if ($this->hasApplication()) {
             $action_name = $action->trimmed('action');
 
-            // CurrentUserDesignAction stores the current user in $cur
-            $user = $action->getCurrentUser();
+            $user = common_current_user();
 
             $flink = null;
 
@@ -294,16 +277,14 @@ class FacebookBridgePlugin extends Plugin
 
                 $action->menuItem(
                     common_local_url('facebooksettings'),
-                    // TRANS: Menu item tab.
+                    // TRANS: Menu item for "Facebook" in user settings.
                     _m('MENU','Facebook'),
-                    // TRANS: Tooltip for menu item "Facebook".
-                    _m('Facebook settings'),
+                    // TRANS: Menu title for "Facebook" in user settings.
+                    _m('Facebook settings.'),
                     $action_name === 'facebooksettings'
                 );
-
             }
         }
-
     }
 
     /*
@@ -324,7 +305,6 @@ class FacebookBridgePlugin extends Plugin
             if (!empty($appId) && !empty($secret)) {
                 return true;
             }
-
         }
 
         return false;
@@ -349,33 +329,42 @@ class FacebookBridgePlugin extends Plugin
      * @param Action $action the current action
      *
      */
-    function onEndShowScripts($action)
+    function onEndShowScripts(Action $action)
     {
         if ($this->needsScripts($action)) {
 
             $action->script('https://connect.facebook.net/en_US/all.js');
 
             $script = <<<ENDOFSCRIPT
-FB.init({appId: %1\$s, session: %2\$s, status: true, cookie: true, xfbml: true});
+function setCookie(name, value) {
+    var date = new Date();
+    date.setTime(date.getTime() + (5 * 60 * 1000)); // 5 mins
+    var expires = "; expires=" + date.toGMTString();
+    document.cookie = name + "=" + value + expires + "; path=/";
+}
+
+FB.init({appId: %1\$s, status: true, cookie: true, xfbml: true, oauth: true});
 
 $('#facebook_button').bind('click', function(event) {
 
     event.preventDefault();
 
     FB.login(function(response) {
-        if (response.session && response.perms) {
-            window.location.href = '%3\$s';
+        if (response.authResponse) {
+            // put the access token in a cookie for the next step
+            setCookie('fb_access_token', response.authResponse.accessToken);
+            window.location.href = '%2\$s';
         } else {
             // NOP (user cancelled login)
         }
-    }, {perms:'read_stream,publish_stream,offline_access,user_status,user_location,user_website,email'});
+    }, {scope:'read_stream,publish_stream,offline_access,user_status,user_location,user_website,email'});
 });
 ENDOFSCRIPT;
 
             $action->inlineScript(
-                sprintf($script,
+                sprintf(
+                    $script,
                     json_encode($this->facebook->getAppId()),
-                    json_encode($this->facebook->getSession()),
                     common_local_url('facebookfinishlogin')
                 )
             );
@@ -387,26 +376,30 @@ ENDOFSCRIPT;
      *
      * @param Action action the current action
      */
-    function onEndLogout($action)
+    function onStartLogout($action)
     {
         if ($this->hasApplication()) {
-            $session = $this->facebook->getSession();
-            $fbuser  = null;
-            $fbuid   = null;
-
-            if ($session) {
-                try {
-                    $fbuid  = $this->facebook->getUser();
-                    $fbuser = $this->facebook->api('/me');
-                 } catch (FacebookApiException $e) {
-                     common_log(LOG_ERROR, $e, __FILE__);
-                 }
-            }
 
-            if (!empty($fbuser)) {
+            $cur = common_current_user();
+            $flink = Foreign_link::getByUserID($cur->id, FACEBOOK_SERVICE);
+
+            if (!empty($flink)) {
+
+                $this->facebook->setAccessToken($flink->credentials);
+
+                if (common_config('singleuser', 'enabled')) {
+                    $user = User::singleUser();
+
+                    $destination = common_local_url(
+                        'showstream',
+                        array('nickname' => $user->nickname)
+                    );
+                } else {
+                    $destination = common_local_url('public');
+                }
 
                 $logoutUrl = $this->facebook->getLogoutUrl(
-                    array('next' => common_local_url('public'))
+                    array('next' => $destination)
                 );
 
                 common_log(
@@ -417,10 +410,13 @@ ENDOFSCRIPT;
                     ),
                     __FILE__
                 );
-                common_debug("LOGOUT URL = $logoutUrl");
+
+                $action->logout();
+
                 common_redirect($logoutUrl, 303);
             }
 
+            return true;
         }
     }
 
@@ -453,7 +449,7 @@ ENDOFSCRIPT;
      *
      * @return boolean hook return
      */
-    function onStartEnqueueNotice($notice, &$transports)
+    function onStartEnqueueNotice(Notice $notice, array &$transports)
     {
         if (self::hasApplication() && $notice->isLocal() && $notice->inScope(null)) {
             array_push($transports, 'facebook');
@@ -526,7 +522,7 @@ ENDOFSCRIPT;
      */
     function onEndFavorNotice(Profile $profile, Notice $notice)
     {
-        $client = new Facebookclient($notice);
+        $client = new Facebookclient($notice, $profile);
         $client->like();
 
         return true;
@@ -542,25 +538,89 @@ ENDOFSCRIPT;
      */
     function onEndDisfavorNotice(Profile $profile, Notice $notice)
     {
-        $client = new Facebookclient($notice);
+        $client = new Facebookclient($notice, $profile);
         $client->unLike();
 
         return true;
     }
 
+    /**
+     * Add links in the user's profile block to their Facebook profile URL.
+     *
+     * @param Profile $profile The profile being shown
+     * @param Array   &$links  Writeable array of arrays (href, text, image).
+     *
+     * @return boolean hook value (true)
+     */
+
+    function onOtherAccountProfiles($profile, &$links)
+    {
+        $fuser = null;
+
+        $flink = Foreign_link::getByUserID($profile->id, FACEBOOK_SERVICE);
+
+        if (!empty($flink)) {
+
+            $fuser = $this->getFacebookUser($flink->foreign_id);
+
+            if (!empty($fuser)) {
+                $links[] = array("href" => $fuser->link,
+                                 "text" => sprintf(_("%s on Facebook"), $fuser->name),
+                                 "image" => $this->path("images/f_logo.png"));
+            }
+        }
+
+        return true;
+    }
+
+    function getFacebookUser($id) {
+
+        $key = Cache::key(sprintf("FacebookBridgePlugin:userdata:%s", $id));
+
+        $c = Cache::instance();
+
+        if ($c) {
+            $obj = $c->get($key);
+            if ($obj) {
+                return $obj;
+            }
+        }
+
+        $url = sprintf("https://graph.facebook.com/%s", $id);
+        $client = new HTTPClient();
+        $resp = $client->get($url);
+
+        if (!$resp->isOK()) {
+            return null;
+        }
+
+        $user = json_decode($resp->getBody());
+
+        if ($user->error) {
+            return null;
+        }
+
+        if ($c) {
+            $c->set($key, $user);
+        }
+
+        return $user;
+    }
+
     /*
      * Add version info for this plugin
      *
      * @param array &$versions    plugin version descriptions
      */
-    function onPluginVersion(&$versions)
+    function onPluginVersion(array &$versions)
     {
         $versions[] = array(
             'name' => 'Facebook Bridge',
-            'version' => STATUSNET_VERSION,
+            'version' => GNUSOCIAL_VERSION,
             'author' => 'Craig Andrews, Zach Copley',
             'homepage' => 'http://status.net/wiki/Plugin:FacebookBridge',
             'rawdescription' =>
+             // TRANS: Plugin description.
             _m('A plugin for integrating StatusNet with Facebook.')
         );