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();
217 * Send a notice to Facebook using the Graph API
223 $fbuid = $this->flink->foreign_id;
227 "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %d",
229 $this->user->nickname,
237 'access_token' => $this->flink->credentials,
238 // XXX: Need to worrry about length of the message?
239 'message' => $this->notice->content
242 $attachments = $this->notice->attachments();
244 if (!empty($attachments)) {
246 // We can only send one attachment with the Graph API :(
248 $first = array_shift($attachments);
250 if (substr($first->mimetype, 0, 6) == 'image/'
253 array('application/x-shockwave-flash', 'audio/mpeg' ))) {
255 $params['picture'] = $first->url;
256 $params['caption'] = 'Click for full size';
257 $params['source'] = $first->url;
262 $result = $this->facebook->api(
263 sprintf('/%s/feed', $fbuid), 'post', $params
267 Notice_to_item::saveNew($this->notice->id, $result['id']);
272 "Posted notice %d as a stream item for %s (%d), fbuid %d",
274 $this->user->nickname,
281 } catch (FacebookApiException $e) {
282 return $this->handleFacebookError($e);
289 * Send a notice to Facebook using the deprecated Old REST API. We need this
290 * for backwards compatibility. Users who signed up for Facebook bridging
291 * using the old Facebook Canvas application do not have an OAuth 2.0
294 function sendOldRest()
298 $canPublish = $this->checkPermission('publish_stream');
299 $canUpdate = $this->checkPermission('status_update');
301 // We prefer to use stream.publish, because it can handle
302 // attachments and returns the ID of the published item
304 if ($canPublish == 1) {
305 $this->restPublishStream();
306 } else if ($canUpdate == 1) {
307 // as a last resort we can just update the user's "status"
308 $this->restStatusUpdate();
311 $msg = 'Not sending notice %d to Facebook because user %s '
312 . '(%d), fbuid %d, does not have \'status_update\' '
313 . 'or \'publish_stream\' permission.';
320 $this->user->nickname,
322 $this->flink->foreign_id
328 } catch (FacebookApiException $e) {
329 return $this->handleFacebookError($e);
336 * Query Facebook to to see if a user has permission
340 * @param $permission the permission to check for - must be either
341 * public_stream or status_update
343 * @return boolean result
345 function checkPermission($permission)
347 if (!in_array($permission, array('publish_stream', 'status_update'))) {
348 throw new ServerException("No such permission!");
351 $fbuid = $this->flink->foreign_id;
355 'Checking for %s permission for user %s (%d), fbuid %d',
357 $this->user->nickname,
364 $hasPermission = $this->facebook->api(
366 'method' => 'users.hasAppPermission',
367 'ext_perm' => $permission,
372 if ($hasPermission == 1) {
376 '%s (%d), fbuid %d has %s permission',
378 $this->user->nickname,
389 $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
390 . 'Facebook returned: %s';
395 $this->user->nickname,
399 var_export($result, true)
410 * Handle a Facebook API Exception
412 * @param FacebookApiException $e the exception
415 function handleFacebookError($e)
417 $fbuid = $this->flink->foreign_id;
418 $errmsg = $e->getMessage();
419 $code = $e->getCode();
421 // The Facebook PHP SDK seems to always set the code attribute
422 // of the Exception to 0; they put the real error code in
425 preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
426 $code = $matches['code'];
429 // XXX: Check for any others?
431 case 100: // Invalid parameter
432 $msg = 'Facebook claims notice %d was posted with an invalid '
433 . 'parameter (error code 100 - %s) Notice details: '
434 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
441 $this->user->nickname,
444 $this->notice->content
450 case 200: // Permissions error
451 case 250: // Updating status requires the extended permission status_update
453 return true; // dequeue
455 case 341: // Feed action request limit reached
456 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
457 . 'for posting notices to Facebook today. Dequeuing '
469 // @fixme: We want to rety at a later time when the throttling has expired
470 // instead of just giving up.
474 $msg = 'Facebook returned an error we don\'t know how to deal with '
475 . 'when posting notice %d. Error code: %d, error message: "%s"'
476 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
477 . 'notice content="%s"]. Dequeing.';
484 $this->user->nickname,
487 $this->notice->content
491 return true; // dequeue
497 * Publish a notice to Facebook as a status update
499 * This is the least preferable way to send a notice to Facebook because
500 * it doesn't support attachments and the API method doesn't return
501 * the ID of the post on Facebook.
504 function restStatusUpdate()
506 $fbuid = $this->flink->foreign_id;
510 "Attempting to post notice %d as a status update for %s (%d), fbuid %d",
512 $this->user->nickname,
519 $result = $this->facebook->api(
521 'method' => 'users.setStatus',
522 'status' => $this->formatMessage(),
523 'status_includes_verb' => true,
528 if ($result == 1) { // 1 is success
533 "Posted notice %s as a status update for %s (%d), fbuid %d",
535 $this->user->nickname,
542 // There is no item ID returned for status update so we can't
543 // save a Notice_to_item mapping
548 "Error posting notice %s as a status update for %s (%d), fbuid %d - error code: %s",
550 $this->user->nickname,
553 $result // will contain 0, or an error
556 throw new FacebookApiException($msg, $result);
561 * Publish a notice to a Facebook user's stream using the old REST API
563 function restPublishStream()
565 $fbuid = $this->flink->foreign_id;
569 'Attempting to post notice %d as stream item for %s (%d) fbuid %d',
571 $this->user->nickname,
578 $fbattachment = $this->formatAttachments();
580 $result = $this->facebook->api(
582 'method' => 'stream.publish',
583 'message' => $this->formatMessage(),
584 'attachment' => $fbattachment,
589 if (!empty($result)) { // result will contain the item ID
592 Notice_to_item::saveNew($this->notice->id, $result);
597 'Posted notice %d as a %s for %s (%d), fbuid %d',
599 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
600 $this->user->nickname,
610 'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
612 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
613 $this->user->nickname,
615 $result, // result will contain an error code
619 throw new FacebookApiException($msg, $result);
624 * Format the text message of a stream item so it's appropriate for
625 * sending to Facebook. If the notice is too long, truncate it, and
626 * add a linkback to the original notice at the end.
628 * @return String $txt the formated message
630 function formatMessage()
632 // Start with the plaintext source of this notice...
633 $txt = $this->notice->content;
635 // Facebook has a 420-char hardcoded max.
636 if (mb_strlen($statustxt) > 420) {
637 $noticeUrl = common_shorten_url($this->notice->uri);
638 $urlLen = mb_strlen($noticeUrl);
639 $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' … ' . $noticeUrl;
646 * Format attachments for the old REST API stream.publish method
648 * Note: Old REST API supports multiple attachments per post
651 function formatAttachments()
653 $attachments = $this->notice->attachments();
655 $fbattachment = array();
656 $fbattachment['media'] = array();
658 foreach($attachments as $attachment)
660 if($enclosure = $attachment->getEnclosure()){
661 $fbmedia = $this->getFacebookMedia($enclosure);
663 $fbmedia = $this->getFacebookMedia($attachment);
666 $fbattachment['media'][]=$fbmedia;
668 $fbattachment['name'] = ($attachment->title ?
669 $attachment->title : $attachment->url);
670 $fbattachment['href'] = $attachment->url;
673 if(count($fbattachment['media'])>0){
674 unset($fbattachment['name']);
675 unset($fbattachment['href']);
677 return $fbattachment;
681 * given a File objects, returns an associative array suitable for Facebook media
683 function getFacebookMedia($attachment)
687 if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
688 $fbmedia['type'] = 'image';
689 $fbmedia['src'] = $attachment->url;
690 $fbmedia['href'] = $attachment->url;
691 } else if ($attachment->mimetype == 'audio/mpeg') {
692 $fbmedia['type'] = 'mp3';
693 $fbmedia['src'] = $attachment->url;
694 }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
695 $fbmedia['type'] = 'flash';
697 // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
698 // says that imgsrc is required... but we have no value to put in it
699 // $fbmedia['imgsrc']='';
701 $fbmedia['swfsrc'] = $attachment->url;
709 * Disconnect a user from Facebook by deleting his Foreign_link.
710 * Notifies the user his account has been disconnected by email.
712 function disconnect()
714 $fbuid = $this->flink->foreign_id;
719 'Removing Facebook link for %s (%d), fbuid %d',
720 $this->user->nickname,
727 $result = $this->flink->delete();
729 if (empty($result)) {
733 'Could not remove Facebook link for %s (%d), fbuid %d',
734 $this->user->nickname,
740 common_log_db_error($flink, 'DELETE', __FILE__);
743 // Notify the user that we are removing their Facebook link
744 if (!empty($this->user->email)) {
745 $result = $this->mailFacebookDisconnect();
749 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
750 . 'about his/her Facebook link being removed.';
756 $this->user->nickname,
766 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
767 . 'about his/her Facebook link being removed because the '
768 . 'user has not set an email address.';
774 $this->user->nickname,
784 * Send a mail message to notify a user that her Facebook link
785 * has been terminated.
787 * @return boolean success flag
789 function mailFacebookDisconnect()
791 $profile = $this->user->getProfile();
793 $siteName = common_config('site', 'name');
795 common_switch_locale($this->user->language);
797 $subject = _m('Your Facebook connection has been removed');
802 We're sorry to inform you we are unable to publish your notice to
803 Facebook, and have removed the connection between your %2$s account and
806 This may have happened because you have removed permission for %2$s
807 to post on your behalf, or perhaps you have deactivated your Facebook
808 account. You can reconnect your %s account to Facebook at any time by
809 logging in with Facebook again.
817 $this->user->nickname,
821 common_switch_locale();
823 $result = mail_to_user($this->user, $subject, $body);
825 if (empty($this->user->password)) {
826 $result = self::emailWarn($this->user);
833 * Send the user an email warning that their account has been
834 * disconnected and he/she has no way to login and must contact
835 * the site administrator for help.
837 * @param User $user the deauthorizing user
840 static function emailWarn($user)
842 $profile = $user->getProfile();
844 $siteName = common_config('site', 'name');
845 $siteEmail = common_config('site', 'email');
847 if (empty($siteEmail)) {
850 "No site email address configured. Please set one."
854 common_switch_locale($user->language);
856 $subject = _m('Contact the %s administrator to retrieve your account');
861 We've noticed you have deauthorized the Facebook connection for your
862 %2$s account. You have not set a password for your %2$s account yet, so
863 you will not be able to login. If you wish to continue using your %2$s
864 account, please contact the site administrator (%3$s) to set a password.
877 common_switch_locale();
879 if (mail_to_user($user, $subject, $body)) {
883 'Sent account lockout warning to %s (%d)',
893 'Unable to send account lockout warning to %s (%d)',
903 * Check to see if we have a mapping to a copy of this notice
906 * @param Notice $notice the notice to check
908 * @return mixed null if it can't find one, or the id of the Facebook
911 static function facebookStatusId($notice)
913 $n2i = Notice_to_item::staticGet('notice_id', $notice->id);
918 return $n2i->item_id;
923 * Save a Foreign_user record of a Facebook user
925 * @param object $fbuser a Facebook Graph API user obj
926 * See: http://developers.facebook.com/docs/reference/api/user
927 * @return mixed $result Id or key
930 static function addFacebookUser($fbuser)
932 // remove any existing, possibly outdated, record
933 $luser = Foreign_user::getForeignUser($fbuser['id'], FACEBOOK_SERVICE);
935 if (!empty($luser)) {
937 $result = $luser->delete();
939 if ($result != false) {
943 'Removed old Facebook user: %s, fbuid %d',
952 $fuser = new Foreign_user();
954 $fuser->nickname = $fbuser['name'];
955 $fuser->uri = $fbuser['link'];
956 $fuser->id = $fbuser['id'];
957 $fuser->service = FACEBOOK_SERVICE;
958 $fuser->created = common_sql_now();
960 $result = $fuser->insert();
962 if (empty($result)) {
966 'Failed to add new Facebook user: %s, fbuid %d',
973 common_log_db_error($fuser, 'INSERT', __FILE__);
978 'Added new Facebook user: %s, fbuid %d',
990 * Remove an item from a Facebook user's feed if we have a mapping
993 function streamRemove()
995 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
997 if (!empty($this->flink) && !empty($n2i)) {
1001 $result = $this->facebook->api(
1003 'method' => 'stream.remove',
1004 'post_id' => $n2i->item_id,
1005 'uid' => $this->flink->foreign_id
1009 if (!empty($result) && result == true) {
1014 'Deleted Facebook item: %s for %s (%d), fbuid %d',
1016 $this->user->nickname,
1018 $this->flink->foreign_id
1026 throw new FaceboookApiException(var_export($result, true));
1029 } catch (FacebookApiException $e) {
1033 'Could not deleted Facebook item: %s for %s (%d), '
1034 . 'fbuid %d - (API error: %s) item already deleted '
1037 $this->user->nickname,
1039 $this->flink->foreign_id,
1049 * Like an item in a Facebook user's feed if we have a mapping
1054 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1056 if (!empty($this->flink) && !empty($n2i)) {
1060 $result = $this->facebook->api(
1062 'method' => 'stream.addlike',
1063 'post_id' => $n2i->item_id,
1064 'uid' => $this->flink->foreign_id
1068 if (!empty($result) && result == true) {
1073 'Added like for item: %s for %s (%d), fbuid %d',
1075 $this->user->nickname,
1077 $this->flink->foreign_id
1083 throw new FacebookApiException(var_export($result, true));
1086 } catch (FacebookApiException $e) {
1090 'Could not like Facebook item: %s for %s (%d), '
1091 . 'fbuid %d (API error: %s)',
1093 $this->user->nickname,
1095 $this->flink->foreign_id,
1105 * Unlike an item in a Facebook user's feed if we have a mapping
1110 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1112 if (!empty($this->flink) && !empty($n2i)) {
1116 $result = $this->facebook->api(
1118 'method' => 'stream.removeLike',
1119 'post_id' => $n2i->item_id,
1120 'uid' => $this->flink->foreign_id
1124 if (!empty($result) && result == true) {
1129 'Removed like for item: %s for %s (%d), fbuid %d',
1131 $this->user->nickname,
1133 $this->flink->foreign_id
1139 throw new FacebookApiException(var_export($result, true));
1142 } catch (FacebookApiException $e) {
1146 'Could not remove like for Facebook item: %s for %s '
1147 . '(%d), fbuid %d (API error: %s)',
1149 $this->user->nickname,
1151 $this->flink->foreign_id,