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();
55 if (empty($this->facebook)) {
56 throw new FacebookApiException(
57 "Could not create Facebook client! Bad application ID or secret?"
61 $this->notice = $notice;
63 $this->flink = Foreign_link::getByUserID(
68 if (!empty($this->flink)) {
69 $this->user = $this->flink->getUser();
74 * Get an instance of the Facebook Graph SDK object
76 * @param string $appId Application
77 * @param string $secret Facebook API secret
79 * @return Facebook A Facebook SDK obj
81 static function getFacebook($appId = null, $secret = null)
83 // Check defaults and configuration for application ID and secret
85 $appId = common_config('facebook', 'appid');
89 $secret = common_config('facebook', 'secret');
92 // If there's no app ID and secret set in the local config, look
94 if (empty($appId) || empty($secret)) {
95 $appId = common_config('facebook', 'global_appid');
96 $secret = common_config('facebook', 'global_secret');
102 "Couldn't find Facebook application ID!",
107 if (empty($secret)) {
110 "Couldn't find Facebook application ID!",
125 * Broadcast a notice to Facebook
127 * @param Notice $notice the notice to send
129 static function facebookBroadcastNotice($notice)
131 common_debug("ZZZZZ facebookBroadcastNotice() - entered ", __FILE__);
132 $client = new Facebookclient($notice);
133 return $client->sendNotice();
137 * Should the notice go to Facebook?
139 function isFacebookBound() {
141 common_debug("ZZZZZ isFacebookBound() - entered", __FILE__);
143 if (empty($this->flink)) {
144 // User hasn't setup bridging
149 if ($this->notice->source == 'Facebook') {
153 'Skipping notice %d because its source is Facebook.',
161 // If the user does not want to broadcast to Facebook, move along
162 if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
166 'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
174 // If it's not a reply, or if the user WANTS to send @-replies,
175 // then, yeah, it can go to Facebook.
176 if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $this->notice->content) ||
177 ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
183 "ZZZZZ isFacebookBound() - notice %d this notice does not go to Facebook",
193 * Determine whether we should send this notice using the Graph API or the
194 * old REST API and then dispatch
196 function sendNotice()
198 // If there's nothing in the credentials field try to send via
201 if ($this->isFacebookBound()) {
202 common_debug("notice is facebook bound", __FILE__);
203 if (empty($this->flink->credentials)) {
204 return $this->sendOldRest();
207 // Otherwise we most likely have an access token
208 return $this->sendGraph();
214 * Send a notice to Facebook using the Graph API
220 $fbuid = $this->flink->foreign_id;
224 "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %d",
226 $this->user->nickname,
234 'access_token' => $this->flink->credentials,
235 // XXX: Need to worrry about length of the message?
236 'message' => $this->notice->content
239 $attachments = $this->notice->attachments();
241 if (!empty($attachments)) {
243 // We can only send one attachment with the Graph API :(
245 $first = array_shift($attachments);
247 if (substr($first->mimetype, 0, 6) == 'image/'
250 array('application/x-shockwave-flash', 'audio/mpeg' ))) {
252 $params['picture'] = $first->url;
253 $params['caption'] = 'Click for full size';
254 $params['source'] = $first->url;
259 $result = $this->facebook->api(
260 sprintf('/%s/feed', $fbuid), 'post', $params
264 Notice_to_item::saveNew($this->notice->id, $result['id']);
269 "Posted notice %d as a stream item for %s (%d), fbuid %d",
271 $this->user->nickname,
278 } catch (FacebookApiException $e) {
279 return $this->handleFacebookError($e);
286 * Send a notice to Facebook using the deprecated Old REST API. We need this
287 * for backwards compatibility. Users who signed up for Facebook bridging
288 * using the old Facebook Canvas application do not have an OAuth 2.0
291 function sendOldRest()
295 $canPublish = $this->checkPermission('publish_stream');
296 $canUpdate = $this->checkPermission('status_update');
298 // We prefer to use stream.publish, because it can handle
299 // attachments and returns the ID of the published item
301 if ($canPublish == 1) {
302 $this->restPublishStream();
303 } else if ($canUpdate == 1) {
304 // as a last resort we can just update the user's "status"
305 $this->restStatusUpdate();
308 $msg = 'Not sending notice %d to Facebook because user %s '
309 . '(%d), fbuid %d, does not have \'status_update\' '
310 . 'or \'publish_stream\' permission.';
317 $this->user->nickname,
319 $this->flink->foreign_id
325 } catch (FacebookApiException $e) {
326 return $this->handleFacebookError($e);
333 * Query Facebook to to see if a user has permission
337 * @param $permission the permission to check for - must be either
338 * public_stream or status_update
340 * @return boolean result
342 function checkPermission($permission)
344 if (!in_array($permission, array('publish_stream', 'status_update'))) {
345 throw new ServerException("No such permission!");
348 $fbuid = $this->flink->foreign_id;
352 'Checking for %s permission for user %s (%d), fbuid %d',
354 $this->user->nickname,
361 $hasPermission = $this->facebook->api(
363 'method' => 'users.hasAppPermission',
364 'ext_perm' => $permission,
369 if ($hasPermission == 1) {
373 '%s (%d), fbuid %d has %s permission',
375 $this->user->nickname,
386 $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
387 . 'Facebook returned: %s';
392 $this->user->nickname,
396 var_export($result, true)
407 * Handle a Facebook API Exception
409 * @param FacebookApiException $e the exception
412 function handleFacebookError($e)
414 $fbuid = $this->flink->foreign_id;
415 $errmsg = $e->getMessage();
416 $code = $e->getCode();
418 // The Facebook PHP SDK seems to always set the code attribute
419 // of the Exception to 0; they put the real error code in
422 preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
423 $code = $matches['code'];
426 // XXX: Check for any others?
428 case 100: // Invalid parameter
429 $msg = 'Facebook claims notice %d was posted with an invalid '
430 . 'parameter (error code 100 - %s) Notice details: '
431 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
438 $this->user->nickname,
441 $this->notice->content
447 case 200: // Permissions error
448 case 250: // Updating status requires the extended permission status_update
450 return true; // dequeue
452 case 341: // Feed action request limit reached
453 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
454 . 'for posting notices to Facebook today. Dequeuing '
466 // @fixme: We want to rety at a later time when the throttling has expired
467 // instead of just giving up.
471 $msg = 'Facebook returned an error we don\'t know how to deal with '
472 . 'when posting notice %d. Error code: %d, error message: "%s"'
473 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
474 . 'notice content="%s"]. Dequeing.';
481 $this->user->nickname,
484 $this->notice->content
488 return true; // dequeue
494 * Publish a notice to Facebook as a status update
496 * This is the least preferable way to send a notice to Facebook because
497 * it doesn't support attachments and the API method doesn't return
498 * the ID of the post on Facebook.
501 function restStatusUpdate()
503 $fbuid = $this->flink->foreign_id;
507 "Attempting to post notice %d as a status update for %s (%d), fbuid %d",
509 $this->user->nickname,
516 $result = $this->facebook->api(
518 'method' => 'users.setStatus',
519 'status' => $this->formatMessage(),
520 'status_includes_verb' => true,
525 if ($result == 1) { // 1 is success
530 "Posted notice %s as a status update for %s (%d), fbuid %d",
532 $this->user->nickname,
539 // There is no item ID returned for status update so we can't
540 // save a Notice_to_item mapping
545 "Error posting notice %s as a status update for %s (%d), fbuid %d - error code: %s",
547 $this->user->nickname,
550 $result // will contain 0, or an error
553 throw new FacebookApiException($msg, $result);
558 * Publish a notice to a Facebook user's stream using the old REST API
560 function restPublishStream()
562 $fbuid = $this->flink->foreign_id;
566 'Attempting to post notice %d as stream item for %s (%d) fbuid %d',
568 $this->user->nickname,
575 $fbattachment = $this->formatAttachments();
577 $result = $this->facebook->api(
579 'method' => 'stream.publish',
580 'message' => $this->formatMessage(),
581 'attachment' => $fbattachment,
586 if (!empty($result)) { // result will contain the item ID
589 Notice_to_item::saveNew($this->notice->id, $result);
594 'Posted notice %d as a %s for %s (%d), fbuid %d',
596 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
597 $this->user->nickname,
607 'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
609 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
610 $this->user->nickname,
612 $result, // result will contain an error code
616 throw new FacebookApiException($msg, $result);
621 * Format the text message of a stream item so it's appropriate for
622 * sending to Facebook. If the notice is too long, truncate it, and
623 * add a linkback to the original notice at the end.
625 * @return String $txt the formated message
627 function formatMessage()
629 // Start with the plaintext source of this notice...
630 $txt = $this->notice->content;
632 // Facebook has a 420-char hardcoded max.
633 if (mb_strlen($statustxt) > 420) {
634 $noticeUrl = common_shorten_url($this->notice->uri);
635 $urlLen = mb_strlen($noticeUrl);
636 $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' … ' . $noticeUrl;
643 * Format attachments for the old REST API stream.publish method
645 * Note: Old REST API supports multiple attachments per post
648 function formatAttachments()
650 $attachments = $this->notice->attachments();
652 $fbattachment = array();
653 $fbattachment['media'] = array();
655 foreach($attachments as $attachment)
657 if($enclosure = $attachment->getEnclosure()){
658 $fbmedia = $this->getFacebookMedia($enclosure);
660 $fbmedia = $this->getFacebookMedia($attachment);
663 $fbattachment['media'][]=$fbmedia;
665 $fbattachment['name'] = ($attachment->title ?
666 $attachment->title : $attachment->url);
667 $fbattachment['href'] = $attachment->url;
670 if(count($fbattachment['media'])>0){
671 unset($fbattachment['name']);
672 unset($fbattachment['href']);
674 return $fbattachment;
678 * given a File objects, returns an associative array suitable for Facebook media
680 function getFacebookMedia($attachment)
684 if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
685 $fbmedia['type'] = 'image';
686 $fbmedia['src'] = $attachment->url;
687 $fbmedia['href'] = $attachment->url;
688 } else if ($attachment->mimetype == 'audio/mpeg') {
689 $fbmedia['type'] = 'mp3';
690 $fbmedia['src'] = $attachment->url;
691 }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
692 $fbmedia['type'] = 'flash';
694 // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
695 // says that imgsrc is required... but we have no value to put in it
696 // $fbmedia['imgsrc']='';
698 $fbmedia['swfsrc'] = $attachment->url;
706 * Disconnect a user from Facebook by deleting his Foreign_link.
707 * Notifies the user his account has been disconnected by email.
709 function disconnect()
711 $fbuid = $this->flink->foreign_id;
716 'Removing Facebook link for %s (%d), fbuid %d',
717 $this->user->nickname,
724 $result = $this->flink->delete();
726 if (empty($result)) {
730 'Could not remove Facebook link for %s (%d), fbuid %d',
731 $this->user->nickname,
737 common_log_db_error($flink, 'DELETE', __FILE__);
740 // Notify the user that we are removing their Facebook link
741 if (!empty($this->user->email)) {
742 $result = $this->mailFacebookDisconnect();
746 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
747 . 'about his/her Facebook link being removed.';
753 $this->user->nickname,
763 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
764 . 'about his/her Facebook link being removed because the '
765 . 'user has not set an email address.';
771 $this->user->nickname,
781 * Send a mail message to notify a user that her Facebook link
782 * has been terminated.
784 * @return boolean success flag
786 function mailFacebookDisconnect()
788 $profile = $this->user->getProfile();
790 $siteName = common_config('site', 'name');
792 common_switch_locale($this->user->language);
794 $subject = _m('Your Facebook connection has been removed');
799 We're sorry to inform you we are unable to publish your notice to
800 Facebook, and have removed the connection between your %2$s account and
803 This may have happened because you have removed permission for %2$s
804 to post on your behalf, or perhaps you have deactivated your Facebook
805 account. You can reconnect your %s account to Facebook at any time by
806 logging in with Facebook again.
814 $this->user->nickname,
818 common_switch_locale();
820 $result = mail_to_user($this->user, $subject, $body);
822 if (empty($this->user->password)) {
823 $result = self::emailWarn($this->user);
830 * Send the user an email warning that their account has been
831 * disconnected and he/she has no way to login and must contact
832 * the site administrator for help.
834 * @param User $user the deauthorizing user
837 static function emailWarn($user)
839 $profile = $user->getProfile();
841 $siteName = common_config('site', 'name');
842 $siteEmail = common_config('site', 'email');
844 if (empty($siteEmail)) {
847 "No site email address configured. Please set one."
851 common_switch_locale($user->language);
853 $subject = _m('Contact the %s administrator to retrieve your account');
858 We've noticed you have deauthorized the Facebook connection for your
859 %2$s account. You have not set a password for your %2$s account yet, so
860 you will not be able to login. If you wish to continue using your %2$s
861 account, please contact the site administrator (%3$s) to set a password.
874 common_switch_locale();
876 if (mail_to_user($user, $subject, $body)) {
880 'Sent account lockout warning to %s (%d)',
890 'Unable to send account lockout warning to %s (%d)',
900 * Check to see if we have a mapping to a copy of this notice
903 * @param Notice $notice the notice to check
905 * @return mixed null if it can't find one, or the id of the Facebook
908 static function facebookStatusId($notice)
910 $n2i = Notice_to_item::staticGet('notice_id', $notice->id);
915 return $n2i->item_id;
920 * Save a Foreign_user record of a Facebook user
922 * @param object $fbuser a Facebook Graph API user obj
923 * See: http://developers.facebook.com/docs/reference/api/user
924 * @return mixed $result Id or key
927 static function addFacebookUser($fbuser)
929 // remove any existing, possibly outdated, record
930 $luser = Foreign_user::getForeignUser($fbuser['id'], FACEBOOK_SERVICE);
932 if (!empty($luser)) {
934 $result = $luser->delete();
936 if ($result != false) {
940 'Removed old Facebook user: %s, fbuid %d',
949 $fuser = new Foreign_user();
951 $fuser->nickname = $fbuser['name'];
952 $fuser->uri = $fbuser['link'];
953 $fuser->id = $fbuser['id'];
954 $fuser->service = FACEBOOK_SERVICE;
955 $fuser->created = common_sql_now();
957 $result = $fuser->insert();
959 if (empty($result)) {
963 'Failed to add new Facebook user: %s, fbuid %d',
970 common_log_db_error($fuser, 'INSERT', __FILE__);
975 'Added new Facebook user: %s, fbuid %d',
987 * Remove an item from a Facebook user's feed if we have a mapping
990 function streamRemove()
992 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
994 if (!empty($this->flink) && !empty($n2i)) {
998 $result = $this->facebook->api(
1000 'method' => 'stream.remove',
1001 'post_id' => $n2i->item_id,
1002 'uid' => $this->flink->foreign_id
1006 if (!empty($result) && result == true) {
1011 'Deleted Facebook item: %s for %s (%d), fbuid %d',
1013 $this->user->nickname,
1015 $this->flink->foreign_id
1023 throw new FaceboookApiException(var_export($result, true));
1026 } catch (FacebookApiException $e) {
1030 'Could not deleted Facebook item: %s for %s (%d), '
1031 . 'fbuid %d - (API error: %s) item already deleted '
1034 $this->user->nickname,
1036 $this->flink->foreign_id,
1046 * Like an item in a Facebook user's feed if we have a mapping
1051 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1053 if (!empty($this->flink) && !empty($n2i)) {
1057 $result = $this->facebook->api(
1059 'method' => 'stream.addlike',
1060 'post_id' => $n2i->item_id,
1061 'uid' => $this->flink->foreign_id
1065 if (!empty($result) && result == true) {
1070 'Added like for item: %s for %s (%d), fbuid %d',
1072 $this->user->nickname,
1074 $this->flink->foreign_id
1080 throw new FacebookApiException(var_export($result, true));
1083 } catch (FacebookApiException $e) {
1087 'Could not like Facebook item: %s for %s (%d), '
1088 . 'fbuid %d (API error: %s)',
1090 $this->user->nickname,
1092 $this->flink->foreign_id,
1102 * Unlike an item in a Facebook user's feed if we have a mapping
1107 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1109 if (!empty($this->flink) && !empty($n2i)) {
1113 $result = $this->facebook->api(
1115 'method' => 'stream.removeLike',
1116 'post_id' => $n2i->item_id,
1117 'uid' => $this->flink->foreign_id
1121 if (!empty($result) && result == true) {
1126 'Removed like for item: %s for %s (%d), fbuid %d',
1128 $this->user->nickname,
1130 $this->flink->foreign_id
1136 throw new FacebookApiException(var_export($result, true));
1139 } catch (FacebookApiException $e) {
1143 'Could not remove like for Facebook item: %s for %s '
1144 . '(%d), fbuid %d (API error: %s)',
1146 $this->user->nickname,
1148 $this->flink->foreign_id,