3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010-2011, StatusNet, Inc.
6 * A plugin for integrating Facebook with StatusNet. Includes single-sign-on
7 * and publishing notices to Facebook using Facebook's Graph API.
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Affero General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Affero General Public License for more details.
21 * You should have received a copy of the GNU Affero General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26 * @author Zach Copley <zach@status.net>
27 * @copyright 2011 StatusNet, Inc.
28 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
29 * @link http://status.net/
32 if (!defined('STATUSNET')) {
36 define("FACEBOOK_SERVICE", 2);
39 * Main class for Facebook Bridge plugin
43 * @author Zach Copley <zach@status.net>
44 * @copyright 2010-2011 StatusNet, Inc.
45 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
46 * @link http://status.net/
48 class FacebookBridgePlugin extends Plugin
50 public $appId; // Facebook application ID
51 public $secret; // Facebook application secret
53 public $facebook = null; // Facebook application instance
54 public $dir = null; // Facebook plugin dir
57 * Initializer for this plugin
59 * Gets an instance of the Facebook API client object
61 * @return boolean hook value; true means continue processing, false means stop.
66 // Allow the id and key to be passed in
67 // Control panel will override
69 if (isset($this->appId)) {
70 $appId = common_config('facebook', 'appid');
80 if (isset($this->secret)) {
81 $secret = common_config('facebook', 'secret');
83 Config::save('facebook', 'secret', $this->secret);
87 $this->facebook = Facebookclient::getFacebook(
96 * Load related modules when needed
98 * @param string $cls Name of the class to be loaded
100 * @return boolean hook value; true means continue processing, false means stop.
102 function onAutoload($cls)
104 $dir = dirname(__FILE__);
108 case 'Facebook': // Facebook PHP SDK
109 include_once $dir . '/extlib/base_facebook.php';
110 include_once $dir . '/extlib/facebook.php';
114 return parent::onAutoload($cls);
118 * Database schema setup
120 * We maintain a table mapping StatusNet notices to Facebook items
125 * @return boolean hook value; true means continue processing, false means stop.
127 function onCheckSchema()
129 $schema = Schema::get();
130 $schema->ensureTable('notice_to_item', Notice_to_item::schemaDef());
135 * Does this $action need the Facebook JavaScripts?
137 function needsScripts($action)
139 static $needy = array(
140 'FacebookloginAction',
141 'FacebookfinishloginAction',
142 'FacebookadminpanelAction',
143 'FacebooksettingsAction'
146 if (in_array(get_class($action), $needy)) {
154 * Map URLs to actions
156 * @param URLMapper $m path-to-action mapper
158 * @return boolean hook value; true means continue processing, false means stop.
160 public function onRouterInitialized(URLMapper $m)
162 // Always add the admin panel route
163 $m->connect('panel/facebook', array('action' => 'facebookadminpanel'));
166 'main/facebooklogin',
167 array('action' => 'facebooklogin')
170 'main/facebookfinishlogin',
171 array('action' => 'facebookfinishlogin')
175 array('action' => 'facebooksettings')
178 'facebook/deauthorize',
179 array('action' => 'facebookdeauthorize')
186 * Add a login tab for Facebook, but only if there's a Facebook
187 * application defined for the plugin to use.
189 * @param Action $action the current action
193 function onEndLoginGroupNav($action)
195 $action_name = $action->trimmed('action');
197 if ($this->hasApplication()) {
200 // TRANS: Menu item for "Facebook" login.
201 common_local_url('facebooklogin'),
202 _m('MENU', 'Facebook'),
203 // TRANS: Menu title for "Facebook" login.
204 _m('Login or register using Facebook.'),
205 'facebooklogin' === $action_name
213 * If the plugin's installed, this should be accessible to admins
215 function onAdminPanelCheck($name, &$isOK)
217 if ($name == 'facebook') {
226 * Add a Facebook tab to the admin panels
228 * @param Widget $nav Admin panel nav
230 * @return boolean hook value
232 function onEndAdminPanelNav($nav)
234 if (AdminPanelAction::canAdmin('facebook')) {
236 $action_name = $nav->action->trimmed('action');
239 common_local_url('facebookadminpanel'),
240 // TRANS: Menu item for "Facebook" in administration panel.
241 _m('MENU','Facebook'),
242 // TRANS: Menu title for "Facebook" in administration panel.
243 _m('Facebook integration configuration.'),
244 $action_name == 'facebookadminpanel',
245 'nav_facebook_admin_panel'
253 * Add a tab for user-level Facebook settings if the user
254 * has a link to Facebook
256 * @param Action $action the current action
260 function onEndConnectSettingsNav($action)
262 if ($this->hasApplication()) {
263 $action_name = $action->trimmed('action');
265 $user = common_current_user();
270 $flink = Foreign_link::getByUserID(
276 if (!empty($flink)) {
279 common_local_url('facebooksettings'),
280 // TRANS: Menu item for "Facebook" in user settings.
281 _m('MENU','Facebook'),
282 // TRANS: Menu title for "Facebook" in user settings.
283 _m('Facebook settings.'),
284 $action_name === 'facebooksettings'
291 * Is there a Facebook application for the plugin to use?
293 * Checks to see if a Facebook application ID and secret
294 * have been configured and a valid Facebook API client
298 function hasApplication()
300 if (!empty($this->facebook)) {
302 $appId = $this->facebook->getAppId();
303 $secret = $this->facebook->getApiSecret();
305 if (!empty($appId) && !empty($secret)) {
314 * Output a Facebook div for the Facebook JavaSsript SDK to use
316 * @param Action $action the current action
319 function onStartShowHeader($action)
321 // output <div id="fb-root"></div> as close to <body> as possible
322 $action->element('div', array('id' => 'fb-root'));
327 * Load the Facebook JavaScript SDK on pages that need them.
329 * @param Action $action the current action
332 function onEndShowScripts($action)
334 if ($this->needsScripts($action)) {
336 $action->script('https://connect.facebook.net/en_US/all.js');
338 $script = <<<ENDOFSCRIPT
339 function setCookie(name, value) {
340 var date = new Date();
341 date.setTime(date.getTime() + (5 * 60 * 1000)); // 5 mins
342 var expires = "; expires=" + date.toGMTString();
343 document.cookie = name + "=" + value + expires + "; path=/";
346 FB.init({appId: %1\$s, status: true, cookie: true, xfbml: true, oauth: true});
348 $('#facebook_button').bind('click', function(event) {
350 event.preventDefault();
352 FB.login(function(response) {
353 if (response.authResponse) {
354 // put the access token in a cookie for the next step
355 setCookie('fb_access_token', response.authResponse.accessToken);
356 window.location.href = '%2\$s';
358 // NOP (user cancelled login)
360 }, {scope:'read_stream,publish_stream,offline_access,user_status,user_location,user_website,email'});
364 $action->inlineScript(
367 json_encode($this->facebook->getAppId()),
368 common_local_url('facebookfinishlogin')
375 * Log the user out of Facebook, per the Facebook authentication guide
377 * @param Action action the current action
379 function onStartLogout($action)
381 if ($this->hasApplication()) {
383 $cur = common_current_user();
384 $flink = Foreign_link::getByUserID($cur->id, FACEBOOK_SERVICE);
386 if (!empty($flink)) {
388 $this->facebook->setAccessToken($flink->credentials);
390 if (common_config('singleuser', 'enabled')) {
391 $user = User::singleUser();
393 $destination = common_local_url(
395 array('nickname' => $user->nickname)
398 $destination = common_local_url('public');
401 $logoutUrl = $this->facebook->getLogoutUrl(
402 array('next' => $destination)
408 "Logging user out of Facebook (fbuid = %s)",
416 common_redirect($logoutUrl, 303);
424 * Add fbml namespace to our HTML, so Facebook's JavaScript SDK can parse
425 * and render XFBML tags
427 * @param Action $action the current action
428 * @param array $attrs array of attributes for the HTML tag
432 function onStartHtmlElement($action, $attrs) {
434 if ($this->needsScripts($action)) {
435 $attrs = array_merge(
437 array('xmlns:fb' => 'http://www.facebook.com/2008/fbml')
445 * Add a Facebook queue item for each notice
447 * @param Notice $notice the notice
448 * @param array &$transports the list of transports (queues)
450 * @return boolean hook return
452 function onStartEnqueueNotice($notice, &$transports)
454 if (self::hasApplication() && $notice->isLocal() && $notice->inScope(null)) {
455 array_push($transports, 'facebook');
461 * Register Facebook notice queue handler
463 * @param QueueManager $manager
465 * @return boolean hook return
467 function onEndInitializeQueueManager($manager)
469 if (self::hasApplication()) {
470 $manager->connect('facebook', 'FacebookQueueHandler');
476 * Use SSL for Facebook stuff
478 * @param string $action name
479 * @param boolean $ssl outval to force SSL
480 * @return mixed hook return value
482 function onSensitiveAction($action, &$ssl)
485 'facebookadminpanel',
488 'facebookfinishlogin'
491 if (in_array($action, $sensitive)) {
500 * If a notice gets deleted, remove the Notice_to_item mapping and
501 * delete the item on Facebook
503 * @param User $user The user doing the deleting
504 * @param Notice $notice The notice getting deleted
506 * @return boolean hook value
508 function onStartDeleteOwnNotice(User $user, Notice $notice)
510 $client = new Facebookclient($notice);
511 $client->streamRemove();
517 * Notify remote users when their notices get favorited.
519 * @param Profile or User $profile of local user doing the faving
520 * @param Notice $notice being favored
521 * @return hook return value
523 function onEndFavorNotice(Profile $profile, Notice $notice)
525 $client = new Facebookclient($notice, $profile);
532 * Notify remote users when their notices get de-favorited.
534 * @param Profile $profile Profile person doing the de-faving
535 * @param Notice $notice Notice being favored
537 * @return hook return value
539 function onEndDisfavorNotice(Profile $profile, Notice $notice)
541 $client = new Facebookclient($notice, $profile);
548 * Add links in the user's profile block to their Facebook profile URL.
550 * @param Profile $profile The profile being shown
551 * @param Array &$links Writeable array of arrays (href, text, image).
553 * @return boolean hook value (true)
556 function onOtherAccountProfiles($profile, &$links)
560 $flink = Foreign_link::getByUserID($profile->id, FACEBOOK_SERVICE);
562 if (!empty($flink)) {
564 $fuser = $this->getFacebookUser($flink->foreign_id);
566 if (!empty($fuser)) {
567 $links[] = array("href" => $fuser->link,
568 "text" => sprintf(_("%s on Facebook"), $fuser->name),
569 "image" => $this->path("images/f_logo.png"));
576 function getFacebookUser($id) {
578 $key = Cache::key(sprintf("FacebookBridgePlugin:userdata:%s", $id));
580 $c = Cache::instance();
583 $obj = $c->get($key);
589 $url = sprintf("https://graph.facebook.com/%s", $id);
590 $client = new HTTPClient();
591 $resp = $client->get($url);
593 if (!$resp->isOK()) {
597 $user = json_decode($resp->getBody());
604 $c->set($key, $user);
611 * Add version info for this plugin
613 * @param array &$versions plugin version descriptions
615 function onPluginVersion(array &$versions)
618 'name' => 'Facebook Bridge',
619 'version' => GNUSOCIAL_VERSION,
620 'author' => 'Craig Andrews, Zach Copley',
621 'homepage' => 'http://status.net/wiki/Plugin:FacebookBridge',
623 // TRANS: Plugin description.
624 _m('A plugin for integrating StatusNet with Facebook.')