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)) {
118 // User hasn't setup bridging
123 if ($this->notice->source == 'Facebook') {
127 'Skipping notice %d because its source is Facebook.',
135 // If the user does not want to broadcast to Facebook, move along
136 if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
140 'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
148 // If it's not a reply, or if the user WANTS to send @-replies,
149 // then, yeah, it can go to Facebook.
150 if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $this->notice->content) ||
151 ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
159 * Determine whether we should send this notice using the Graph API or the
160 * old REST API and then dispatch
162 function sendNotice()
164 // If there's nothing in the credentials field try to send via
167 if ($this->isFacebookBound()) {
168 common_debug("notice is facebook bound", __FILE__);
169 if (empty($this->flink->credentials)) {
170 return $this->sendOldRest();
173 // Otherwise we most likely have an access token
174 return $this->sendGraph();
180 * Send a notice to Facebook using the Graph API
186 $fbuid = $this->flink->foreign_id;
190 "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %d",
192 $this->user->nickname,
200 'access_token' => $this->flink->credentials,
201 // XXX: Need to worrry about length of the message?
202 'message' => $this->notice->content
205 $attachments = $this->notice->attachments();
207 if (!empty($attachments)) {
209 // We can only send one attachment with the Graph API :(
211 $first = array_shift($attachments);
213 if (substr($first->mimetype, 0, 6) == 'image/'
216 array('application/x-shockwave-flash', 'audio/mpeg' ))) {
218 $params['picture'] = $first->url;
219 $params['caption'] = 'Click for full size';
220 $params['source'] = $first->url;
225 $result = $this->facebook->api(
226 sprintf('/%s/feed', $fbuid), 'post', $params
230 Notice_to_item::saveNew($this->notice->id, $result['id']);
235 "Posted notice %d as a stream item for %s (%d), fbuid %d",
237 $this->user->nickname,
244 } catch (FacebookApiException $e) {
245 return $this->handleFacebookError($e);
252 * Send a notice to Facebook using the deprecated Old REST API. We need this
253 * for backwards compatibility. Users who signed up for Facebook bridging
254 * using the old Facebook Canvas application do not have an OAuth 2.0
257 function sendOldRest()
261 $canPublish = $this->checkPermission('publish_stream');
262 $canUpdate = $this->checkPermission('status_update');
264 // We prefer to use stream.publish, because it can handle
265 // attachments and returns the ID of the published item
267 if ($canPublish == 1) {
268 $this->restPublishStream();
269 } else if ($canUpdate == 1) {
270 // as a last resort we can just update the user's "status"
271 $this->restStatusUpdate();
274 $msg = 'Not sending notice %d to Facebook because user %s '
275 . '(%d), fbuid %d, does not have \'status_update\' '
276 . 'or \'publish_stream\' permission.';
283 $this->user->nickname,
285 $this->flink->foreign_id
291 } catch (FacebookApiException $e) {
292 return $this->handleFacebookError($e);
299 * Query Facebook to to see if a user has permission
303 * @param $permission the permission to check for - must be either
304 * public_stream or status_update
306 * @return boolean result
308 function checkPermission($permission)
310 if (!in_array($permission, array('publish_stream', 'status_update'))) {
311 throw new ServerException("No such permission!");
314 $fbuid = $this->flink->foreign_id;
318 'Checking for %s permission for user %s (%d), fbuid %d',
320 $this->user->nickname,
327 $hasPermission = $this->facebook->api(
329 'method' => 'users.hasAppPermission',
330 'ext_perm' => $permission,
335 if ($hasPermission == 1) {
339 '%s (%d), fbuid %d has %s permission',
341 $this->user->nickname,
352 $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
353 . 'Facebook returned: %s';
358 $this->user->nickname,
362 var_export($result, true)
373 * Handle a Facebook API Exception
375 * @param FacebookApiException $e the exception
378 function handleFacebookError($e)
380 $fbuid = $this->flink->foreign_id;
381 $errmsg = $e->getMessage();
382 $code = $e->getCode();
384 // The Facebook PHP SDK seems to always set the code attribute
385 // of the Exception to 0; they put the real error code in
388 preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
389 $code = $matches['code'];
392 // XXX: Check for any others?
394 case 100: // Invalid parameter
395 $msg = 'Facebook claims notice %d was posted with an invalid '
396 . 'parameter (error code 100 - %s) Notice details: '
397 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
404 $this->user->nickname,
407 $this->notice->content
413 case 200: // Permissions error
414 case 250: // Updating status requires the extended permission status_update
416 return true; // dequeue
418 case 341: // Feed action request limit reached
419 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
420 . 'for posting notices to Facebook today. Dequeuing '
432 // @fixme: We want to rety at a later time when the throttling has expired
433 // instead of just giving up.
437 $msg = 'Facebook returned an error we don\'t know how to deal with '
438 . 'when posting notice %d. Error code: %d, error message: "%s"'
439 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
440 . 'notice content="%s"]. Dequeing.';
447 $this->user->nickname,
450 $this->notice->content
454 return true; // dequeue
460 * Publish a notice to Facebook as a status update
462 * This is the least preferable way to send a notice to Facebook because
463 * it doesn't support attachments and the API method doesn't return
464 * the ID of the post on Facebook.
467 function restStatusUpdate()
469 $fbuid = $this->flink->foreign_id;
473 "Attempting to post notice %d as a status update for %s (%d), fbuid %d",
475 $this->user->nickname,
482 $result = $this->facebook->api(
484 'method' => 'users.setStatus',
485 'status' => $this->formatMessage(),
486 'status_includes_verb' => true,
491 if ($result == 1) { // 1 is success
496 "Posted notice %s as a status update for %s (%d), fbuid %d",
498 $this->user->nickname,
505 // There is no item ID returned for status update so we can't
506 // save a Notice_to_item mapping
511 "Error posting notice %s as a status update for %s (%d), fbuid %d - error code: %s",
513 $this->user->nickname,
516 $result // will contain 0, or an error
519 throw new FacebookApiException($msg, $result);
524 * Publish a notice to a Facebook user's stream using the old REST API
526 function restPublishStream()
528 $fbuid = $this->flink->foreign_id;
532 'Attempting to post notice %d as stream item for %s (%d) fbuid %d',
534 $this->user->nickname,
541 $fbattachment = $this->formatAttachments();
543 $result = $this->facebook->api(
545 'method' => 'stream.publish',
546 'message' => $this->formatMessage(),
547 'attachment' => $fbattachment,
552 if (!empty($result)) { // result will contain the item ID
555 Notice_to_item::saveNew($this->notice->id, $result);
560 'Posted notice %d as a %s for %s (%d), fbuid %d',
562 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
563 $this->user->nickname,
573 'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
575 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
576 $this->user->nickname,
578 $result, // result will contain an error code
582 throw new FacebookApiException($msg, $result);
587 * Format the text message of a stream item so it's appropriate for
588 * sending to Facebook. If the notice is too long, truncate it, and
589 * add a linkback to the original notice at the end.
591 * @return String $txt the formated message
593 function formatMessage()
595 // Start with the plaintext source of this notice...
596 $txt = $this->notice->content;
598 // Facebook has a 420-char hardcoded max.
599 if (mb_strlen($statustxt) > 420) {
600 $noticeUrl = common_shorten_url($this->notice->uri);
601 $urlLen = mb_strlen($noticeUrl);
602 $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' … ' . $noticeUrl;
609 * Format attachments for the old REST API stream.publish method
611 * Note: Old REST API supports multiple attachments per post
614 function formatAttachments()
616 $attachments = $this->notice->attachments();
618 $fbattachment = array();
619 $fbattachment['media'] = array();
621 foreach($attachments as $attachment)
623 if($enclosure = $attachment->getEnclosure()){
624 $fbmedia = $this->getFacebookMedia($enclosure);
626 $fbmedia = $this->getFacebookMedia($attachment);
629 $fbattachment['media'][]=$fbmedia;
631 $fbattachment['name'] = ($attachment->title ?
632 $attachment->title : $attachment->url);
633 $fbattachment['href'] = $attachment->url;
636 if(count($fbattachment['media'])>0){
637 unset($fbattachment['name']);
638 unset($fbattachment['href']);
640 return $fbattachment;
644 * given a File objects, returns an associative array suitable for Facebook media
646 function getFacebookMedia($attachment)
650 if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
651 $fbmedia['type'] = 'image';
652 $fbmedia['src'] = $attachment->url;
653 $fbmedia['href'] = $attachment->url;
654 } else if ($attachment->mimetype == 'audio/mpeg') {
655 $fbmedia['type'] = 'mp3';
656 $fbmedia['src'] = $attachment->url;
657 }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
658 $fbmedia['type'] = 'flash';
660 // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
661 // says that imgsrc is required... but we have no value to put in it
662 // $fbmedia['imgsrc']='';
664 $fbmedia['swfsrc'] = $attachment->url;
672 * Disconnect a user from Facebook by deleting his Foreign_link.
673 * Notifies the user his account has been disconnected by email.
675 function disconnect()
677 $fbuid = $this->flink->foreign_id;
682 'Removing Facebook link for %s (%d), fbuid %d',
683 $this->user->nickname,
690 $result = $this->flink->delete();
692 if (empty($result)) {
696 'Could not remove Facebook link for %s (%d), fbuid %d',
697 $this->user->nickname,
703 common_log_db_error($flink, 'DELETE', __FILE__);
706 // Notify the user that we are removing their Facebook link
707 if (!empty($this->user->email)) {
708 $result = $this->mailFacebookDisconnect();
712 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
713 . 'about his/her Facebook link being removed.';
719 $this->user->nickname,
729 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
730 . 'about his/her Facebook link being removed because the '
731 . 'user has not set an email address.';
737 $this->user->nickname,
747 * Send a mail message to notify a user that her Facebook link
748 * has been terminated.
750 * @return boolean success flag
752 function mailFacebookDisconnect()
754 $profile = $this->user->getProfile();
756 $siteName = common_config('site', 'name');
758 common_switch_locale($this->user->language);
760 $subject = _m('Your Facebook connection has been removed');
765 We're sorry to inform you we are unable to publish your notice to
766 Facebook, and have removed the connection between your %2$s account and
769 This may have happened because you have removed permission for %2$s
770 to post on your behalf, or perhaps you have deactivated your Facebook
771 account. You can reconnect your %s account to Facebook at any time by
772 logging in with Facebook again.
780 $this->user->nickname,
784 common_switch_locale();
786 $result = mail_to_user($this->user, $subject, $body);
788 if (empty($this->user->password)) {
789 $result = self::emailWarn($this->user);
796 * Send the user an email warning that their account has been
797 * disconnected and he/she has no way to login and must contact
798 * the site administrator for help.
800 * @param User $user the deauthorizing user
803 static function emailWarn($user)
805 $profile = $user->getProfile();
807 $siteName = common_config('site', 'name');
808 $siteEmail = common_config('site', 'email');
810 if (empty($siteEmail)) {
813 "No site email address configured. Please set one."
817 common_switch_locale($user->language);
819 $subject = _m('Contact the %s administrator to retrieve your account');
824 We've noticed you have deauthorized the Facebook connection for your
825 %2$s account. You have not set a password for your %2$s account yet, so
826 you will not be able to login. If you wish to continue using your %2$s
827 account, please contact the site administrator (%3$s) to set a password.
840 common_switch_locale();
842 if (mail_to_user($user, $subject, $body)) {
846 'Sent account lockout warning to %s (%d)',
856 'Unable to send account lockout warning to %s (%d)',
866 * Check to see if we have a mapping to a copy of this notice
869 * @param Notice $notice the notice to check
871 * @return mixed null if it can't find one, or the id of the Facebook
874 static function facebookStatusId($notice)
876 $n2i = Notice_to_item::staticGet('notice_id', $notice->id);
881 return $n2i->item_id;
886 * Save a Foreign_user record of a Facebook user
888 * @param object $fbuser a Facebook Graph API user obj
889 * See: http://developers.facebook.com/docs/reference/api/user
890 * @return mixed $result Id or key
893 static function addFacebookUser($fbuser)
895 // remove any existing, possibly outdated, record
896 $luser = Foreign_user::getForeignUser($fbuser['id'], FACEBOOK_SERVICE);
898 if (!empty($luser)) {
900 $result = $luser->delete();
902 if ($result != false) {
906 'Removed old Facebook user: %s, fbuid %d',
915 $fuser = new Foreign_user();
917 $fuser->nickname = $fbuser['name'];
918 $fuser->uri = $fbuser['link'];
919 $fuser->id = $fbuser['id'];
920 $fuser->service = FACEBOOK_SERVICE;
921 $fuser->created = common_sql_now();
923 $result = $fuser->insert();
925 if (empty($result)) {
929 'Failed to add new Facebook user: %s, fbuid %d',
936 common_log_db_error($fuser, 'INSERT', __FILE__);
941 'Added new Facebook user: %s, fbuid %d',
953 * Remove an item from a Facebook user's feed if we have a mapping
956 function streamRemove()
958 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
960 if (!empty($this->flink) && !empty($n2i)) {
964 $result = $this->facebook->api(
966 'method' => 'stream.remove',
967 'post_id' => $n2i->item_id,
968 'uid' => $this->flink->foreign_id
972 if (!empty($result) && result == true) {
977 'Deleted Facebook item: %s for %s (%d), fbuid %d',
979 $this->user->nickname,
981 $this->flink->foreign_id
989 throw new FaceboookApiException(var_export($result, true));
992 } catch (FacebookApiException $e) {
996 'Could not deleted Facebook item: %s for %s (%d), '
997 . 'fbuid %d - (API error: %s) item already deleted '
1000 $this->user->nickname,
1002 $this->flink->foreign_id,
1012 * Like an item in a Facebook user's feed if we have a mapping
1017 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1019 if (!empty($this->flink) && !empty($n2i)) {
1023 $result = $this->facebook->api(
1025 'method' => 'stream.addlike',
1026 'post_id' => $n2i->item_id,
1027 'uid' => $this->flink->foreign_id
1031 if (!empty($result) && result == true) {
1036 'Added like for item: %s for %s (%d), fbuid %d',
1038 $this->user->nickname,
1040 $this->flink->foreign_id
1046 throw new FacebookApiException(var_export($result, true));
1049 } catch (FacebookApiException $e) {
1053 'Could not like Facebook item: %s for %s (%d), '
1054 . 'fbuid %d (API error: %s)',
1056 $this->user->nickname,
1058 $this->flink->foreign_id,
1068 * Unlike an item in a Facebook user's feed if we have a mapping
1073 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1075 if (!empty($this->flink) && !empty($n2i)) {
1079 $result = $this->facebook->api(
1081 'method' => 'stream.removeLike',
1082 'post_id' => $n2i->item_id,
1083 'uid' => $this->flink->foreign_id
1087 if (!empty($result) && result == true) {
1092 'Removed like for item: %s for %s (%d), fbuid %d',
1094 $this->user->nickname,
1096 $this->flink->foreign_id
1102 throw new FacebookApiException(var_export($result, true));
1105 } catch (FacebookApiException $e) {
1109 'Could not remove like for Facebook item: %s for %s '
1110 . '(%d), fbuid %d (API error: %s)',
1112 $this->user->nickname,
1114 $this->flink->foreign_id,