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 $this->user = $this->flink->getUser();
65 * Get an instance of the Facebook Graph SDK object
67 * @param string $appId Application
68 * @param string $secret Facebook API secret
70 * @return Facebook A Facebook SDK obj
72 static function getFacebook($appId = null, $secret = null)
74 // Check defaults and configuration for application ID and secret
76 $appId = common_config('facebook', 'appid');
80 $secret = common_config('facebook', 'secret');
83 // If there's no app ID and secret set in the local config, look
85 if (empty($appId) || empty($secret)) {
86 $appId = common_config('facebook', 'global_appid');
87 $secret = common_config('facebook', 'global_secret');
100 * Broadcast a notice to Facebook
102 * @param Notice $notice the notice to send
104 static function facebookBroadcastNotice($notice)
106 $client = new Facebookclient($notice);
107 return $client->sendNotice();
111 * Should the notice go to Facebook?
113 function isFacebookBound() {
115 if (empty($this->flink)) {
119 "No Foreign_link to Facebook for the author of notice %d.",
128 if ($this->notice->source == 'Facebook') {
132 'Skipping notice %d because its source is Facebook.',
140 // If the user does not want to broadcast to Facebook, move along
141 if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
145 'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
153 // If it's not a reply, or if the user WANTS to send @-replies,
154 // then, yeah, it can go to Facebook.
155 if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $this->notice->content) ||
156 ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
164 * Determine whether we should send this notice using the Graph API or the
165 * old REST API and then dispatch
167 function sendNotice()
169 // If there's nothing in the credentials field try to send via
172 if ($this->isFacebookBound()) {
173 common_debug("notice is facebook bound", __FILE__);
174 if (empty($this->flink->credentials)) {
175 return $this->sendOldRest();
178 // Otherwise we most likely have an access token
179 return $this->sendGraph();
185 "Skipping notice %d - not bound for Facebook",
194 * Send a notice to Facebook using the Graph API
200 $fbuid = $this->flink->foreign_id;
204 "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %d",
206 $this->user->nickname,
214 'access_token' => $this->flink->credentials,
215 // XXX: Need to worrry about length of the message?
216 'message' => $this->notice->content
219 $attachments = $this->notice->attachments();
221 if (!empty($attachments)) {
223 // We can only send one attachment with the Graph API :(
225 $first = array_shift($attachments);
227 if (substr($first->mimetype, 0, 6) == 'image/'
230 array('application/x-shockwave-flash', 'audio/mpeg' ))) {
232 $params['picture'] = $first->url;
233 $params['caption'] = 'Click for full size';
234 $params['source'] = $first->url;
239 $result = $this->facebook->api(
240 sprintf('/%s/feed', $fbuid), 'post', $params
244 Notice_to_item::saveNew($this->notice->id, $result['id']);
249 "Posted notice %d as a stream item for %s (%d), fbuid %d",
251 $this->user->nickname,
258 } catch (FacebookApiException $e) {
259 return $this->handleFacebookError($e);
266 * Send a notice to Facebook using the deprecated Old REST API. We need this
267 * for backwards compatibility. Users who signed up for Facebook bridging
268 * using the old Facebook Canvas application do not have an OAuth 2.0
271 function sendOldRest()
275 $canPublish = $this->checkPermission('publish_stream');
276 $canUpdate = $this->checkPermission('status_update');
278 // We prefer to use stream.publish, because it can handle
279 // attachments and returns the ID of the published item
281 if ($canPublish == 1) {
282 $this->restPublishStream();
283 } else if ($canUpdate == 1) {
284 // as a last resort we can just update the user's "status"
285 $this->restStatusUpdate();
288 $msg = 'Not sending notice %d to Facebook because user %s '
289 . '(%d), fbuid %d, does not have \'status_update\' '
290 . 'or \'publish_stream\' permission.';
297 $this->user->nickname,
299 $this->flink->foreign_id
305 } catch (FacebookApiException $e) {
306 return $this->handleFacebookError($e);
313 * Query Facebook to to see if a user has permission
317 * @param $permission the permission to check for - must be either
318 * public_stream or status_update
320 * @return boolean result
322 function checkPermission($permission)
324 if (!in_array($permission, array('publish_stream', 'status_update'))) {
325 throw new ServerException("No such permission!");
328 $fbuid = $this->flink->foreign_id;
332 'Checking for %s permission for user %s (%d), fbuid %d',
334 $this->user->nickname,
341 $hasPermission = $this->facebook->api(
343 'method' => 'users.hasAppPermission',
344 'ext_perm' => $permission,
349 if ($hasPermission == 1) {
353 '%s (%d), fbuid %d has %s permission',
355 $this->user->nickname,
366 $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
367 . 'Facebook returned: %s';
372 $this->user->nickname,
376 var_export($result, true)
387 * Handle a Facebook API Exception
389 * @param FacebookApiException $e the exception
392 function handleFacebookError($e)
394 $fbuid = $this->flink->foreign_id;
395 $errmsg = $e->getMessage();
396 $code = $e->getCode();
398 // The Facebook PHP SDK seems to always set the code attribute
399 // of the Exception to 0; they put the real error code in
402 preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
403 $code = $matches['code'];
406 // XXX: Check for any others?
408 case 100: // Invalid parameter
409 $msg = 'Facebook claims notice %d was posted with an invalid '
410 . 'parameter (error code 100 - %s) Notice details: '
411 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
418 $this->user->nickname,
421 $this->notice->content
428 // @fixme: Facebook returns these 2xx permission errors sometimes
429 // FOR NO GOOD REASON AT ALL! It would be better to retry a few times
430 // over an extended period of time to instead of immediately
433 case 200: // Permissions error
434 case 250: // Updating status requires the extended permission status_update
436 return true; // dequeue
438 case 341: // Feed action request limit reached
439 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
440 . 'for posting notices to Facebook today. Dequeuing '
452 // @fixme: We want to rety at a later time when the throttling has expired
453 // instead of just giving up.
457 $msg = 'Facebook returned an error we don\'t know how to deal with '
458 . 'when posting notice %d. Error code: %d, error message: "%s"'
459 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
460 . 'notice content="%s"]. Dequeing.';
467 $this->user->nickname,
470 $this->notice->content
474 return true; // dequeue
480 * Publish a notice to Facebook as a status update
482 * This is the least preferable way to send a notice to Facebook because
483 * it doesn't support attachments and the API method doesn't return
484 * the ID of the post on Facebook.
487 function restStatusUpdate()
489 $fbuid = $this->flink->foreign_id;
493 "Attempting to post notice %d as a status update for %s (%d), fbuid %d",
495 $this->user->nickname,
502 $result = $this->facebook->api(
504 'method' => 'users.setStatus',
505 'status' => $this->formatMessage(),
506 'status_includes_verb' => true,
511 if ($result == 1) { // 1 is success
516 "Posted notice %s as a status update for %s (%d), fbuid %d",
518 $this->user->nickname,
525 // There is no item ID returned for status update so we can't
526 // save a Notice_to_item mapping
531 "Error posting notice %s as a status update for %s (%d), fbuid %d - error code: %s",
533 $this->user->nickname,
536 $result // will contain 0, or an error
539 throw new FacebookApiException($msg, $result);
544 * Publish a notice to a Facebook user's stream using the old REST API
546 function restPublishStream()
548 $fbuid = $this->flink->foreign_id;
552 'Attempting to post notice %d as stream item for %s (%d) fbuid %d',
554 $this->user->nickname,
561 $fbattachment = $this->formatAttachments();
563 $result = $this->facebook->api(
565 'method' => 'stream.publish',
566 'message' => $this->formatMessage(),
567 'attachment' => $fbattachment,
572 if (!empty($result)) { // result will contain the item ID
575 Notice_to_item::saveNew($this->notice->id, $result);
580 'Posted notice %d as a %s for %s (%d), fbuid %d',
582 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
583 $this->user->nickname,
593 'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
595 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
596 $this->user->nickname,
598 $result, // result will contain an error code
602 throw new FacebookApiException($msg, $result);
607 * Format the text message of a stream item so it's appropriate for
608 * sending to Facebook. If the notice is too long, truncate it, and
609 * add a linkback to the original notice at the end.
611 * @return String $txt the formated message
613 function formatMessage()
615 // Start with the plaintext source of this notice...
616 $txt = $this->notice->content;
618 // Facebook has a 420-char hardcoded max.
619 if (mb_strlen($statustxt) > 420) {
620 $noticeUrl = common_shorten_url($this->notice->uri);
621 $urlLen = mb_strlen($noticeUrl);
622 $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' … ' . $noticeUrl;
629 * Format attachments for the old REST API stream.publish method
631 * Note: Old REST API supports multiple attachments per post
634 function formatAttachments()
636 $attachments = $this->notice->attachments();
638 $fbattachment = array();
639 $fbattachment['media'] = array();
641 foreach($attachments as $attachment)
643 if($enclosure = $attachment->getEnclosure()){
644 $fbmedia = $this->getFacebookMedia($enclosure);
646 $fbmedia = $this->getFacebookMedia($attachment);
649 $fbattachment['media'][]=$fbmedia;
651 $fbattachment['name'] = ($attachment->title ?
652 $attachment->title : $attachment->url);
653 $fbattachment['href'] = $attachment->url;
656 if(count($fbattachment['media'])>0){
657 unset($fbattachment['name']);
658 unset($fbattachment['href']);
660 return $fbattachment;
664 * given a File objects, returns an associative array suitable for Facebook media
666 function getFacebookMedia($attachment)
670 if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
671 $fbmedia['type'] = 'image';
672 $fbmedia['src'] = $attachment->url;
673 $fbmedia['href'] = $attachment->url;
674 } else if ($attachment->mimetype == 'audio/mpeg') {
675 $fbmedia['type'] = 'mp3';
676 $fbmedia['src'] = $attachment->url;
677 }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
678 $fbmedia['type'] = 'flash';
680 // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
681 // says that imgsrc is required... but we have no value to put in it
682 // $fbmedia['imgsrc']='';
684 $fbmedia['swfsrc'] = $attachment->url;
692 * Disconnect a user from Facebook by deleting his Foreign_link.
693 * Notifies the user his account has been disconnected by email.
695 function disconnect()
697 $fbuid = $this->flink->foreign_id;
702 'Removing Facebook link for %s (%d), fbuid %d',
703 $this->user->nickname,
710 $result = $this->flink->delete();
712 if (empty($result)) {
716 'Could not remove Facebook link for %s (%d), fbuid %d',
717 $this->user->nickname,
723 common_log_db_error($flink, 'DELETE', __FILE__);
726 // Notify the user that we are removing their Facebook link
727 if (!empty($this->user->email)) {
728 $result = $this->mailFacebookDisconnect();
732 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
733 . 'about his/her Facebook link being removed.';
739 $this->user->nickname,
749 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
750 . 'about his/her Facebook link being removed because the '
751 . 'user has not set an email address.';
757 $this->user->nickname,
767 * Send a mail message to notify a user that her Facebook link
768 * has been terminated.
770 * @return boolean success flag
772 function mailFacebookDisconnect()
774 $profile = $this->user->getProfile();
776 $siteName = common_config('site', 'name');
778 common_switch_locale($this->user->language);
780 $subject = _m('Your Facebook connection has been removed');
785 We're sorry to inform you we are unable to publish your notice to
786 Facebook, and have removed the connection between your %2$s account and
789 This may have happened because you have removed permission for %2$s
790 to post on your behalf, or perhaps you have deactivated your Facebook
791 account. You can reconnect your %s account to Facebook at any time by
792 logging in with Facebook again.
800 $this->user->nickname,
804 common_switch_locale();
806 $result = mail_to_user($this->user, $subject, $body);
808 if (empty($this->user->password)) {
809 $result = self::emailWarn($this->user);
816 * Send the user an email warning that their account has been
817 * disconnected and he/she has no way to login and must contact
818 * the site administrator for help.
820 * @param User $user the deauthorizing user
823 static function emailWarn($user)
825 $profile = $user->getProfile();
827 $siteName = common_config('site', 'name');
828 $siteEmail = common_config('site', 'email');
830 if (empty($siteEmail)) {
833 "No site email address configured. Please set one."
837 common_switch_locale($user->language);
839 $subject = _m('Contact the %s administrator to retrieve your account');
844 We've noticed you have deauthorized the Facebook connection for your
845 %2$s account. You have not set a password for your %2$s account yet, so
846 you will not be able to login. If you wish to continue using your %2$s
847 account, please contact the site administrator (%3$s) to set a password.
860 common_switch_locale();
862 if (mail_to_user($user, $subject, $body)) {
866 'Sent account lockout warning to %s (%d)',
876 'Unable to send account lockout warning to %s (%d)',
886 * Check to see if we have a mapping to a copy of this notice
889 * @param Notice $notice the notice to check
891 * @return mixed null if it can't find one, or the id of the Facebook
894 static function facebookStatusId($notice)
896 $n2i = Notice_to_item::staticGet('notice_id', $notice->id);
901 return $n2i->item_id;
906 * Save a Foreign_user record of a Facebook user
908 * @param object $fbuser a Facebook Graph API user obj
909 * See: http://developers.facebook.com/docs/reference/api/user
910 * @return mixed $result Id or key
913 static function addFacebookUser($fbuser)
915 // remove any existing, possibly outdated, record
916 $luser = Foreign_user::getForeignUser($fbuser['id'], FACEBOOK_SERVICE);
918 if (!empty($luser)) {
920 $result = $luser->delete();
922 if ($result != false) {
926 'Removed old Facebook user: %s, fbuid %d',
935 $fuser = new Foreign_user();
937 $fuser->nickname = $fbuser['name'];
938 $fuser->uri = $fbuser['link'];
939 $fuser->id = $fbuser['id'];
940 $fuser->service = FACEBOOK_SERVICE;
941 $fuser->created = common_sql_now();
943 $result = $fuser->insert();
945 if (empty($result)) {
949 'Failed to add new Facebook user: %s, fbuid %d',
956 common_log_db_error($fuser, 'INSERT', __FILE__);
961 'Added new Facebook user: %s, fbuid %d',
973 * Remove an item from a Facebook user's feed if we have a mapping
976 function streamRemove()
978 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
980 if (!empty($this->flink) && !empty($n2i)) {
982 $result = $this->facebook->api(
984 'method' => 'stream.remove',
985 'post_id' => $n2i->item_id,
986 'uid' => $this->flink->foreign_id
990 if (!empty($result) && result == true) {
995 'Deleted Facebook item: %s for %s (%d), fbuid %d',
997 $this->user->nickname,
999 $this->flink->foreign_id
1011 'Could not deleted Facebook item: %s for %s (%d), fbuid %d',
1013 $this->user->nickname,
1015 $this->flink->foreign_id
1024 * Like an item in a Facebook user's feed if we have a mapping
1029 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1031 if (!empty($this->flink) && !empty($n2i)) {
1033 $result = $this->facebook->api(
1035 'method' => 'stream.addlike',
1036 'post_id' => $n2i->item_id,
1037 'uid' => $this->flink->foreign_id
1041 if (!empty($result) && result == true) {
1046 'Added like for item: %s for %s (%d), fbuid %d',
1048 $this->user->nickname,
1050 $this->flink->foreign_id
1060 'Could not like Facebook item: %s for %s (%d), fbuid %d',
1062 $this->user->nickname,
1064 $this->flink->foreign_id
1073 * Unlike an item in a Facebook user's feed if we have a mapping
1078 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1080 if (!empty($this->flink) && !empty($n2i)) {
1082 $result = $this->facebook->api(
1084 'method' => 'stream.removeLike',
1085 'post_id' => $n2i->item_id,
1086 'uid' => $this->flink->foreign_id
1090 if (!empty($result) && result == true) {
1095 'Removed like for item: %s for %s (%d), fbuid %d',
1097 $this->user->nickname,
1099 $this->flink->foreign_id
1109 'Could not remove like for Facebook item: %s for %s (%d), fbuid %d',
1111 $this->user->nickname,
1113 $this->flink->foreign_id