3 * StatusNet, the distributed open-source microblogging tool
5 * Class for communicating with Facebook
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Zach Copley <zach@status.net>
26 * @copyright 2009-2010 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28 * @link http://status.net/
31 if (!defined('STATUSNET')) {
36 * Class for communication with Facebook
40 * @author Zach Copley <zach@status.net>
41 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
42 * @link http://status.net/
46 protected $facebook = null; // Facebook Graph client obj
47 protected $flink = null; // Foreign_link StatusNet -> Facebook
48 protected $notice = null; // The user's notice
49 protected $user = null; // Sender of the notice
51 function __construct($notice)
53 $this->facebook = self::getFacebook();
54 $this->notice = $notice;
56 $this->flink = Foreign_link::getByUserID(
61 if (!empty($this->flink)) {
62 $this->user = $this->flink->getUser();
67 * Get an instance of the Facebook Graph SDK object
69 * @param string $appId Application
70 * @param string $secret Facebook API secret
72 * @return Facebook A Facebook SDK obj
74 static function getFacebook($appId = null, $secret = null)
76 // Check defaults and configuration for application ID and secret
78 $appId = common_config('facebook', 'appid');
82 $secret = common_config('facebook', 'secret');
85 // If there's no app ID and secret set in the local config, look
87 if (empty($appId) || empty($secret)) {
88 $appId = common_config('facebook', 'global_appid');
89 $secret = common_config('facebook', 'global_secret');
102 * Broadcast a notice to Facebook
104 * @param Notice $notice the notice to send
106 static function facebookBroadcastNotice($notice)
108 $client = new Facebookclient($notice);
109 return $client->sendNotice();
113 * Should the notice go to Facebook?
115 function isFacebookBound() {
117 if (empty($this->flink)) {
121 "No Foreign_link to Facebook for the author of notice %d.",
130 if ($this->notice->source == 'Facebook') {
134 'Skipping notice %d because its source is Facebook.',
142 // If the user does not want to broadcast to Facebook, move along
143 if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
147 'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
155 // If it's not a reply, or if the user WANTS to send @-replies,
156 // then, yeah, it can go to Facebook.
157 if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $this->notice->content) ||
158 ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
166 * Determine whether we should send this notice using the Graph API or the
167 * old REST API and then dispatch
169 function sendNotice()
171 // If there's nothing in the credentials field try to send via
174 if ($this->isFacebookBound()) {
175 common_debug("notice is facebook bound", __FILE__);
176 if (empty($this->flink->credentials)) {
177 return $this->sendOldRest();
180 // Otherwise we most likely have an access token
181 return $this->sendGraph();
187 "Skipping notice %d - not bound for Facebook",
196 * Send a notice to Facebook using the Graph API
202 $fbuid = $this->flink->foreign_id;
206 "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %d",
208 $this->user->nickname,
216 'access_token' => $this->flink->credentials,
217 // XXX: Need to worrry about length of the message?
218 'message' => $this->notice->content
221 $attachments = $this->notice->attachments();
223 if (!empty($attachments)) {
225 // We can only send one attachment with the Graph API :(
227 $first = array_shift($attachments);
229 if (substr($first->mimetype, 0, 6) == 'image/'
232 array('application/x-shockwave-flash', 'audio/mpeg' ))) {
234 $params['picture'] = $first->url;
235 $params['caption'] = 'Click for full size';
236 $params['source'] = $first->url;
241 $result = $this->facebook->api(
242 sprintf('/%s/feed', $fbuid), 'post', $params
246 Notice_to_item::saveNew($this->notice->id, $result['id']);
251 "Posted notice %d as a stream item for %s (%d), fbuid %d",
253 $this->user->nickname,
260 } catch (FacebookApiException $e) {
261 return $this->handleFacebookError($e);
268 * Send a notice to Facebook using the deprecated Old REST API. We need this
269 * for backwards compatibility. Users who signed up for Facebook bridging
270 * using the old Facebook Canvas application do not have an OAuth 2.0
273 function sendOldRest()
277 $canPublish = $this->checkPermission('publish_stream');
278 $canUpdate = $this->checkPermission('status_update');
280 // We prefer to use stream.publish, because it can handle
281 // attachments and returns the ID of the published item
283 if ($canPublish == 1) {
284 $this->restPublishStream();
285 } else if ($canUpdate == 1) {
286 // as a last resort we can just update the user's "status"
287 $this->restStatusUpdate();
290 $msg = 'Not sending notice %d to Facebook because user %s '
291 . '(%d), fbuid %d, does not have \'status_update\' '
292 . 'or \'publish_stream\' permission.';
299 $this->user->nickname,
301 $this->flink->foreign_id
307 } catch (FacebookApiException $e) {
308 return $this->handleFacebookError($e);
315 * Query Facebook to to see if a user has permission
319 * @param $permission the permission to check for - must be either
320 * public_stream or status_update
322 * @return boolean result
324 function checkPermission($permission)
326 if (!in_array($permission, array('publish_stream', 'status_update'))) {
327 throw new ServerException("No such permission!");
330 $fbuid = $this->flink->foreign_id;
334 'Checking for %s permission for user %s (%d), fbuid %d',
336 $this->user->nickname,
343 $hasPermission = $this->facebook->api(
345 'method' => 'users.hasAppPermission',
346 'ext_perm' => $permission,
351 if ($hasPermission == 1) {
355 '%s (%d), fbuid %d has %s permission',
357 $this->user->nickname,
368 $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
369 . 'Facebook returned: %s';
374 $this->user->nickname,
378 var_export($result, true)
389 * Handle a Facebook API Exception
391 * @param FacebookApiException $e the exception
394 function handleFacebookError($e)
396 $fbuid = $this->flink->foreign_id;
397 $errmsg = $e->getMessage();
398 $code = $e->getCode();
400 // The Facebook PHP SDK seems to always set the code attribute
401 // of the Exception to 0; they put the real error code in
404 preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
405 $code = $matches['code'];
408 // XXX: Check for any others?
410 case 100: // Invalid parameter
411 $msg = 'Facebook claims notice %d was posted with an invalid '
412 . 'parameter (error code 100 - %s) Notice details: '
413 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
420 $this->user->nickname,
423 $this->notice->content
429 case 200: // Permissions error
430 case 250: // Updating status requires the extended permission status_update
432 return true; // dequeue
434 case 341: // Feed action request limit reached
435 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
436 . 'for posting notices to Facebook today. Dequeuing '
448 // @fixme: We want to rety at a later time when the throttling has expired
449 // instead of just giving up.
453 $msg = 'Facebook returned an error we don\'t know how to deal with '
454 . 'when posting notice %d. Error code: %d, error message: "%s"'
455 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
456 . 'notice content="%s"]. Dequeing.';
463 $this->user->nickname,
466 $this->notice->content
470 return true; // dequeue
476 * Publish a notice to Facebook as a status update
478 * This is the least preferable way to send a notice to Facebook because
479 * it doesn't support attachments and the API method doesn't return
480 * the ID of the post on Facebook.
483 function restStatusUpdate()
485 $fbuid = $this->flink->foreign_id;
489 "Attempting to post notice %d as a status update for %s (%d), fbuid %d",
491 $this->user->nickname,
498 $result = $this->facebook->api(
500 'method' => 'users.setStatus',
501 'status' => $this->formatMessage(),
502 'status_includes_verb' => true,
507 if ($result == 1) { // 1 is success
512 "Posted notice %s as a status update for %s (%d), fbuid %d",
514 $this->user->nickname,
521 // There is no item ID returned for status update so we can't
522 // save a Notice_to_item mapping
527 "Error posting notice %s as a status update for %s (%d), fbuid %d - error code: %s",
529 $this->user->nickname,
532 $result // will contain 0, or an error
535 throw new FacebookApiException($msg, $result);
540 * Publish a notice to a Facebook user's stream using the old REST API
542 function restPublishStream()
544 $fbuid = $this->flink->foreign_id;
548 'Attempting to post notice %d as stream item for %s (%d) fbuid %d',
550 $this->user->nickname,
557 $fbattachment = $this->formatAttachments();
559 $result = $this->facebook->api(
561 'method' => 'stream.publish',
562 'message' => $this->formatMessage(),
563 'attachment' => $fbattachment,
568 if (!empty($result)) { // result will contain the item ID
571 Notice_to_item::saveNew($this->notice->id, $result);
576 'Posted notice %d as a %s for %s (%d), fbuid %d',
578 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
579 $this->user->nickname,
589 'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
591 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
592 $this->user->nickname,
594 $result, // result will contain an error code
598 throw new FacebookApiException($msg, $result);
603 * Format the text message of a stream item so it's appropriate for
604 * sending to Facebook. If the notice is too long, truncate it, and
605 * add a linkback to the original notice at the end.
607 * @return String $txt the formated message
609 function formatMessage()
611 // Start with the plaintext source of this notice...
612 $txt = $this->notice->content;
614 // Facebook has a 420-char hardcoded max.
615 if (mb_strlen($statustxt) > 420) {
616 $noticeUrl = common_shorten_url($this->notice->uri);
617 $urlLen = mb_strlen($noticeUrl);
618 $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' … ' . $noticeUrl;
625 * Format attachments for the old REST API stream.publish method
627 * Note: Old REST API supports multiple attachments per post
630 function formatAttachments()
632 $attachments = $this->notice->attachments();
634 $fbattachment = array();
635 $fbattachment['media'] = array();
637 foreach($attachments as $attachment)
639 if($enclosure = $attachment->getEnclosure()){
640 $fbmedia = $this->getFacebookMedia($enclosure);
642 $fbmedia = $this->getFacebookMedia($attachment);
645 $fbattachment['media'][]=$fbmedia;
647 $fbattachment['name'] = ($attachment->title ?
648 $attachment->title : $attachment->url);
649 $fbattachment['href'] = $attachment->url;
652 if(count($fbattachment['media'])>0){
653 unset($fbattachment['name']);
654 unset($fbattachment['href']);
656 return $fbattachment;
660 * given a File objects, returns an associative array suitable for Facebook media
662 function getFacebookMedia($attachment)
666 if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
667 $fbmedia['type'] = 'image';
668 $fbmedia['src'] = $attachment->url;
669 $fbmedia['href'] = $attachment->url;
670 } else if ($attachment->mimetype == 'audio/mpeg') {
671 $fbmedia['type'] = 'mp3';
672 $fbmedia['src'] = $attachment->url;
673 }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
674 $fbmedia['type'] = 'flash';
676 // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
677 // says that imgsrc is required... but we have no value to put in it
678 // $fbmedia['imgsrc']='';
680 $fbmedia['swfsrc'] = $attachment->url;
688 * Disconnect a user from Facebook by deleting his Foreign_link.
689 * Notifies the user his account has been disconnected by email.
691 function disconnect()
693 $fbuid = $this->flink->foreign_id;
698 'Removing Facebook link for %s (%d), fbuid %d',
699 $this->user->nickname,
706 $result = $this->flink->delete();
708 if (empty($result)) {
712 'Could not remove Facebook link for %s (%d), fbuid %d',
713 $this->user->nickname,
719 common_log_db_error($flink, 'DELETE', __FILE__);
722 // Notify the user that we are removing their Facebook link
723 if (!empty($this->user->email)) {
724 $result = $this->mailFacebookDisconnect();
728 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
729 . 'about his/her Facebook link being removed.';
735 $this->user->nickname,
745 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
746 . 'about his/her Facebook link being removed because the '
747 . 'user has not set an email address.';
753 $this->user->nickname,
763 * Send a mail message to notify a user that her Facebook link
764 * has been terminated.
766 * @return boolean success flag
768 function mailFacebookDisconnect()
770 $profile = $this->user->getProfile();
772 $siteName = common_config('site', 'name');
774 common_switch_locale($this->user->language);
776 $subject = _m('Your Facebook connection has been removed');
781 We're sorry to inform you we are unable to publish your notice to
782 Facebook, and have removed the connection between your %2$s account and
785 This may have happened because you have removed permission for %2$s
786 to post on your behalf, or perhaps you have deactivated your Facebook
787 account. You can reconnect your %s account to Facebook at any time by
788 logging in with Facebook again.
796 $this->user->nickname,
800 common_switch_locale();
802 $result = mail_to_user($this->user, $subject, $body);
804 if (empty($this->user->password)) {
805 $result = self::emailWarn($this->user);
812 * Send the user an email warning that their account has been
813 * disconnected and he/she has no way to login and must contact
814 * the site administrator for help.
816 * @param User $user the deauthorizing user
819 static function emailWarn($user)
821 $profile = $user->getProfile();
823 $siteName = common_config('site', 'name');
824 $siteEmail = common_config('site', 'email');
826 if (empty($siteEmail)) {
829 "No site email address configured. Please set one."
833 common_switch_locale($user->language);
835 $subject = _m('Contact the %s administrator to retrieve your account');
840 We've noticed you have deauthorized the Facebook connection for your
841 %2$s account. You have not set a password for your %2$s account yet, so
842 you will not be able to login. If you wish to continue using your %2$s
843 account, please contact the site administrator (%3$s) to set a password.
856 common_switch_locale();
858 if (mail_to_user($user, $subject, $body)) {
862 'Sent account lockout warning to %s (%d)',
872 'Unable to send account lockout warning to %s (%d)',
882 * Check to see if we have a mapping to a copy of this notice
885 * @param Notice $notice the notice to check
887 * @return mixed null if it can't find one, or the id of the Facebook
890 static function facebookStatusId($notice)
892 $n2i = Notice_to_item::staticGet('notice_id', $notice->id);
897 return $n2i->item_id;
902 * Save a Foreign_user record of a Facebook user
904 * @param object $fbuser a Facebook Graph API user obj
905 * See: http://developers.facebook.com/docs/reference/api/user
906 * @return mixed $result Id or key
909 static function addFacebookUser($fbuser)
911 // remove any existing, possibly outdated, record
912 $luser = Foreign_user::getForeignUser($fbuser['id'], FACEBOOK_SERVICE);
914 if (!empty($luser)) {
916 $result = $luser->delete();
918 if ($result != false) {
922 'Removed old Facebook user: %s, fbuid %d',
931 $fuser = new Foreign_user();
933 $fuser->nickname = $fbuser['name'];
934 $fuser->uri = $fbuser['link'];
935 $fuser->id = $fbuser['id'];
936 $fuser->service = FACEBOOK_SERVICE;
937 $fuser->created = common_sql_now();
939 $result = $fuser->insert();
941 if (empty($result)) {
945 'Failed to add new Facebook user: %s, fbuid %d',
952 common_log_db_error($fuser, 'INSERT', __FILE__);
957 'Added new Facebook user: %s, fbuid %d',
969 * Remove an item from a Facebook user's feed if we have a mapping
972 function streamRemove()
974 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
976 if (!empty($this->flink) && !empty($n2i)) {
980 $result = $this->facebook->api(
982 'method' => 'stream.remove',
983 'post_id' => $n2i->item_id,
984 'uid' => $this->flink->foreign_id
988 if (!empty($result) && result == true) {
993 'Deleted Facebook item: %s for %s (%d), fbuid %d',
995 $this->user->nickname,
997 $this->flink->foreign_id
1005 throw new FaceboookApiException(var_export($result, true));
1008 } catch (FacebookApiException $e) {
1012 'Could not deleted Facebook item: %s for %s (%d), '
1013 . 'fbuid %d - (API error: %s) item already deleted '
1016 $this->user->nickname,
1018 $this->flink->foreign_id,
1028 * Like an item in a Facebook user's feed if we have a mapping
1033 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1035 if (!empty($this->flink) && !empty($n2i)) {
1039 $result = $this->facebook->api(
1041 'method' => 'stream.addlike',
1042 'post_id' => $n2i->item_id,
1043 'uid' => $this->flink->foreign_id
1047 if (!empty($result) && result == true) {
1052 'Added like for item: %s for %s (%d), fbuid %d',
1054 $this->user->nickname,
1056 $this->flink->foreign_id
1062 throw new FacebookApiException(var_export($result, true));
1065 } catch (FacebookApiException $e) {
1069 'Could not like Facebook item: %s for %s (%d), '
1070 . 'fbuid %d (API error: %s)',
1072 $this->user->nickname,
1074 $this->flink->foreign_id,
1084 * Unlike an item in a Facebook user's feed if we have a mapping
1089 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1091 if (!empty($this->flink) && !empty($n2i)) {
1095 $result = $this->facebook->api(
1097 'method' => 'stream.removeLike',
1098 'post_id' => $n2i->item_id,
1099 'uid' => $this->flink->foreign_id
1103 if (!empty($result) && result == true) {
1108 'Removed like for item: %s for %s (%d), fbuid %d',
1110 $this->user->nickname,
1112 $this->flink->foreign_id
1118 throw new FacebookApiException(var_export($result, true));
1121 } catch (FacebookApiException $e) {
1125 'Could not remove like for Facebook item: %s for %s '
1126 . '(%d), fbuid %d (API error: %s)',
1128 $this->user->nickname,
1130 $this->flink->foreign_id,