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';
112 case 'FacebookloginAction':
113 case 'FacebookfinishloginAction':
114 case 'FacebookadminpanelAction':
115 case 'FacebooksettingsAction':
116 case 'FacebookdeauthorizeAction':
117 include_once $dir . '/actions/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
119 case 'Facebookclient':
120 case 'FacebookQueueHandler':
121 include_once $dir . '/lib/' . strtolower($cls) . '.php';
123 case 'Notice_to_item':
124 include_once $dir . '/classes/' . $cls . '.php';
132 * Database schema setup
134 * We maintain a table mapping StatusNet notices to Facebook items
139 * @return boolean hook value; true means continue processing, false means stop.
141 function onCheckSchema()
143 $schema = Schema::get();
144 $schema->ensureTable('notice_to_item', Notice_to_item::schemaDef());
149 * Does this $action need the Facebook JavaScripts?
151 function needsScripts($action)
153 static $needy = array(
154 'FacebookloginAction',
155 'FacebookfinishloginAction',
156 'FacebookadminpanelAction',
157 'FacebooksettingsAction'
160 if (in_array(get_class($action), $needy)) {
168 * Map URLs to actions
170 * @param Net_URL_Mapper $m path-to-action mapper
172 * @return boolean hook value; true means continue processing, false means stop.
174 function onRouterInitialized($m)
176 // Always add the admin panel route
177 $m->connect('panel/facebook', array('action' => 'facebookadminpanel'));
180 'main/facebooklogin',
181 array('action' => 'facebooklogin')
184 'main/facebookfinishlogin',
185 array('action' => 'facebookfinishlogin')
189 array('action' => 'facebooksettings')
192 'facebook/deauthorize',
193 array('action' => 'facebookdeauthorize')
200 * Add a login tab for Facebook, but only if there's a Facebook
201 * application defined for the plugin to use.
203 * @param Action $action the current action
207 function onEndLoginGroupNav($action)
209 $action_name = $action->trimmed('action');
211 if ($this->hasApplication()) {
214 // TRANS: Menu item for "Facebook" login.
215 common_local_url('facebooklogin'),
216 _m('MENU', 'Facebook'),
217 // TRANS: Menu title for "Facebook" login.
218 _m('Login or register using Facebook.'),
219 'facebooklogin' === $action_name
227 * If the plugin's installed, this should be accessible to admins
229 function onAdminPanelCheck($name, &$isOK)
231 if ($name == 'facebook') {
240 * Add a Facebook tab to the admin panels
242 * @param Widget $nav Admin panel nav
244 * @return boolean hook value
246 function onEndAdminPanelNav($nav)
248 if (AdminPanelAction::canAdmin('facebook')) {
250 $action_name = $nav->action->trimmed('action');
253 common_local_url('facebookadminpanel'),
254 // TRANS: Menu item for "Facebook" in administration panel.
255 _m('MENU','Facebook'),
256 // TRANS: Menu title for "Facebook" in administration panel.
257 _m('Facebook integration configuration.'),
258 $action_name == 'facebookadminpanel',
259 'nav_facebook_admin_panel'
267 * Add a tab for user-level Facebook settings if the user
268 * has a link to Facebook
270 * @param Action $action the current action
274 function onEndConnectSettingsNav($action)
276 if ($this->hasApplication()) {
277 $action_name = $action->trimmed('action');
279 $user = common_current_user();
284 $flink = Foreign_link::getByUserID(
290 if (!empty($flink)) {
293 common_local_url('facebooksettings'),
294 // TRANS: Menu item for "Facebook" in user settings.
295 _m('MENU','Facebook'),
296 // TRANS: Menu title for "Facebook" in user settings.
297 _m('Facebook settings.'),
298 $action_name === 'facebooksettings'
305 * Is there a Facebook application for the plugin to use?
307 * Checks to see if a Facebook application ID and secret
308 * have been configured and a valid Facebook API client
312 function hasApplication()
314 if (!empty($this->facebook)) {
316 $appId = $this->facebook->getAppId();
317 $secret = $this->facebook->getApiSecret();
319 if (!empty($appId) && !empty($secret)) {
328 * Output a Facebook div for the Facebook JavaSsript SDK to use
330 * @param Action $action the current action
333 function onStartShowHeader($action)
335 // output <div id="fb-root"></div> as close to <body> as possible
336 $action->element('div', array('id' => 'fb-root'));
341 * Load the Facebook JavaScript SDK on pages that need them.
343 * @param Action $action the current action
346 function onEndShowScripts($action)
348 if ($this->needsScripts($action)) {
350 $action->script('https://connect.facebook.net/en_US/all.js');
352 $script = <<<ENDOFSCRIPT
353 function setCookie(name, value) {
354 var date = new Date();
355 date.setTime(date.getTime() + (5 * 60 * 1000)); // 5 mins
356 var expires = "; expires=" + date.toGMTString();
357 document.cookie = name + "=" + value + expires + "; path=/";
360 FB.init({appId: %1\$s, status: true, cookie: true, xfbml: true, oauth: true});
362 $('#facebook_button').bind('click', function(event) {
364 event.preventDefault();
366 FB.login(function(response) {
367 if (response.authResponse) {
368 // put the access token in a cookie for the next step
369 setCookie('fb_access_token', response.authResponse.accessToken);
370 window.location.href = '%2\$s';
372 // NOP (user cancelled login)
374 }, {scope:'read_stream,publish_stream,offline_access,user_status,user_location,user_website,email'});
378 $action->inlineScript(
381 json_encode($this->facebook->getAppId()),
382 common_local_url('facebookfinishlogin')
389 * Log the user out of Facebook, per the Facebook authentication guide
391 * @param Action action the current action
393 function onStartLogout($action)
395 if ($this->hasApplication()) {
397 $cur = common_current_user();
398 $flink = Foreign_link::getByUserID($cur->id, FACEBOOK_SERVICE);
400 if (!empty($flink)) {
402 $this->facebook->setAccessToken($flink->credentials);
404 if (common_config('singleuser', 'enabled')) {
405 $user = User::singleUser();
407 $destination = common_local_url(
409 array('nickname' => $user->nickname)
412 $destination = common_local_url('public');
415 $logoutUrl = $this->facebook->getLogoutUrl(
416 array('next' => $destination)
422 "Logging user out of Facebook (fbuid = %s)",
430 common_redirect($logoutUrl, 303);
431 return false; // probably never get here, but hey
439 * Add fbml namespace to our HTML, so Facebook's JavaScript SDK can parse
440 * and render XFBML tags
442 * @param Action $action the current action
443 * @param array $attrs array of attributes for the HTML tag
447 function onStartHtmlElement($action, $attrs) {
449 if ($this->needsScripts($action)) {
450 $attrs = array_merge(
452 array('xmlns:fb' => 'http://www.facebook.com/2008/fbml')
460 * Add a Facebook queue item for each notice
462 * @param Notice $notice the notice
463 * @param array &$transports the list of transports (queues)
465 * @return boolean hook return
467 function onStartEnqueueNotice($notice, &$transports)
469 if (self::hasApplication() && $notice->isLocal() && $notice->inScope(null)) {
470 array_push($transports, 'facebook');
476 * Register Facebook notice queue handler
478 * @param QueueManager $manager
480 * @return boolean hook return
482 function onEndInitializeQueueManager($manager)
484 if (self::hasApplication()) {
485 $manager->connect('facebook', 'FacebookQueueHandler');
491 * Use SSL for Facebook stuff
493 * @param string $action name
494 * @param boolean $ssl outval to force SSL
495 * @return mixed hook return value
497 function onSensitiveAction($action, &$ssl)
500 'facebookadminpanel',
503 'facebookfinishlogin'
506 if (in_array($action, $sensitive)) {
515 * If a notice gets deleted, remove the Notice_to_item mapping and
516 * delete the item on Facebook
518 * @param User $user The user doing the deleting
519 * @param Notice $notice The notice getting deleted
521 * @return boolean hook value
523 function onStartDeleteOwnNotice(User $user, Notice $notice)
525 $client = new Facebookclient($notice);
526 $client->streamRemove();
532 * Notify remote users when their notices get favorited.
534 * @param Profile or User $profile of local user doing the faving
535 * @param Notice $notice being favored
536 * @return hook return value
538 function onEndFavorNotice(Profile $profile, Notice $notice)
540 $client = new Facebookclient($notice, $profile);
547 * Notify remote users when their notices get de-favorited.
549 * @param Profile $profile Profile person doing the de-faving
550 * @param Notice $notice Notice being favored
552 * @return hook return value
554 function onEndDisfavorNotice(Profile $profile, Notice $notice)
556 $client = new Facebookclient($notice, $profile);
563 * Add links in the user's profile block to their Facebook profile URL.
565 * @param Profile $profile The profile being shown
566 * @param Array &$links Writeable array of arrays (href, text, image).
568 * @return boolean hook value (true)
571 function onOtherAccountProfiles($profile, &$links)
575 $flink = Foreign_link::getByUserID($profile->id, FACEBOOK_SERVICE);
577 if (!empty($flink)) {
579 $fuser = $this->getFacebookUser($flink->foreign_id);
581 if (!empty($fuser)) {
582 $links[] = array("href" => $fuser->link,
583 "text" => sprintf(_("%s on Facebook"), $fuser->name),
584 "image" => $this->path("images/f_logo.png"));
591 function getFacebookUser($id) {
593 $key = Cache::key(sprintf("FacebookBridgePlugin:userdata:%s", $id));
595 $c = Cache::instance();
598 $obj = $c->get($key);
604 $url = sprintf("https://graph.facebook.com/%s", $id);
605 $client = new HTTPClient();
606 $resp = $client->get($url);
608 if (!$resp->isOK()) {
612 $user = json_decode($resp->getBody());
619 $c->set($key, $user);
626 * Add version info for this plugin
628 * @param array &$versions plugin version descriptions
630 function onPluginVersion(&$versions)
633 'name' => 'Facebook Bridge',
634 'version' => STATUSNET_VERSION,
635 'author' => 'Craig Andrews, Zach Copley',
636 'homepage' => 'http://status.net/wiki/Plugin:FacebookBridge',
638 // TRANS: Plugin description.
639 _m('A plugin for integrating StatusNet with Facebook.')