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 common_debug('Facebook broadcast');
107 $client = new Facebookclient($notice);
108 return $client->sendNotice();
112 * Should the notice go to Facebook?
114 function isFacebookBound() {
116 if (empty($this->flink)) {
120 "No Foreign_link to Facebook for the author of notice %d.",
129 if ($this->notice->source == 'Facebook') {
133 'Skipping notice %d because its source is Facebook.',
141 // If the user does not want to broadcast to Facebook, move along
142 if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
146 'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
154 // If it's not a reply, or if the user WANTS to send @-replies,
155 // then, yeah, it can go to Facebook.
156 if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $this->notice->content) ||
157 ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
165 * Determine whether we should send this notice using the Graph API or the
166 * old REST API and then dispatch
168 function sendNotice()
170 // If there's nothing in the credentials field try to send via
173 if ($this->isFacebookBound()) {
174 common_debug("notice is facebook bound", __FILE__);
175 if (empty($this->flink->credentials)) {
176 return $this->sendOldRest();
179 // Otherwise we most likely have an access token
180 return $this->sendGraph();
186 "Skipping notice %d - not bound for Facebook",
195 * Send a notice to Facebook using the Graph API
201 $fbuid = $this->flink->foreign_id;
205 "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %s",
207 $this->user->nickname,
215 'access_token' => $this->flink->credentials,
216 // XXX: Need to worrry about length of the message?
217 'message' => $this->notice->content
220 $attachments = $this->notice->attachments();
222 if (!empty($attachments)) {
224 // We can only send one attachment with the Graph API :(
226 $first = array_shift($attachments);
228 if (substr($first->mimetype, 0, 6) == 'image/'
231 array('application/x-shockwave-flash', 'audio/mpeg' ))) {
233 $params['picture'] = $first->url;
234 $params['caption'] = 'Click for full size';
235 $params['source'] = $first->url;
240 $result = $this->facebook->api(
241 sprintf('/%s/feed', $fbuid), 'post', $params
245 Notice_to_item::saveNew($this->notice->id, $result['id']);
250 "Posted notice %d as a stream item for %s (%d), fbuid %s",
252 $this->user->nickname,
259 } catch (FacebookApiException $e) {
260 return $this->handleFacebookError($e);
267 * Send a notice to Facebook using the deprecated Old REST API. We need this
268 * for backwards compatibility. Users who signed up for Facebook bridging
269 * using the old Facebook Canvas application do not have an OAuth 2.0
272 function sendOldRest()
276 $canPublish = $this->checkPermission('publish_stream');
277 $canUpdate = $this->checkPermission('status_update');
279 // We prefer to use stream.publish, because it can handle
280 // attachments and returns the ID of the published item
282 if ($canPublish == 1) {
283 $this->restPublishStream();
284 } else if ($canUpdate == 1) {
285 // as a last resort we can just update the user's "status"
286 $this->restStatusUpdate();
289 $msg = 'Not sending notice %d to Facebook because user %s '
290 . '(%d), fbuid %s, does not have \'status_update\' '
291 . 'or \'publish_stream\' permission.';
298 $this->user->nickname,
300 $this->flink->foreign_id
306 } catch (FacebookApiException $e) {
307 return $this->handleFacebookError($e);
314 * Query Facebook to to see if a user has permission
318 * @param $permission the permission to check for - must be either
319 * public_stream or status_update
321 * @return boolean result
323 function checkPermission($permission)
325 if (!in_array($permission, array('publish_stream', 'status_update'))) {
326 throw new ServerException("No such permission!");
329 $fbuid = $this->flink->foreign_id;
333 'Checking for %s permission for user %s (%d), fbuid %s',
335 $this->user->nickname,
342 $hasPermission = $this->facebook->api(
344 'method' => 'users.hasAppPermission',
345 'ext_perm' => $permission,
350 if ($hasPermission == 1) {
354 '%s (%d), fbuid %s has %s permission',
356 $this->user->nickname,
367 $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
368 . 'Facebook returned: %s';
373 $this->user->nickname,
377 var_export($result, true)
388 * Handle a Facebook API Exception
390 * @param FacebookApiException $e the exception
393 function handleFacebookError($e)
395 $fbuid = $this->flink->foreign_id;
396 $errmsg = $e->getMessage();
397 $code = $e->getCode();
399 // The Facebook PHP SDK seems to always set the code attribute
400 // of the Exception to 0; they put the real error code in
403 preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
404 $code = $matches['code'];
407 // XXX: Check for any others?
409 case 100: // Invalid parameter
410 $msg = 'Facebook claims notice %d was posted with an invalid '
411 . 'parameter (error code 100 - %s) Notice details: '
412 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
419 $this->user->nickname,
422 $this->notice->content
428 case 200: // Permissions error
429 case 250: // Updating status requires the extended permission status_update
431 return true; // dequeue
433 case 341: // Feed action request limit reached
434 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
435 . 'for posting notices to Facebook today. Dequeuing '
447 // @fixme: We want to rety at a later time when the throttling has expired
448 // instead of just giving up.
452 $msg = 'Facebook returned an error we don\'t know how to deal with '
453 . 'when posting notice %d. Error code: %d, error message: "%s"'
454 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
455 . 'notice content="%s"]. Dequeing.';
462 $this->user->nickname,
465 $this->notice->content
469 return true; // dequeue
475 * Publish a notice to Facebook as a status update
477 * This is the least preferable way to send a notice to Facebook because
478 * it doesn't support attachments and the API method doesn't return
479 * the ID of the post on Facebook.
482 function restStatusUpdate()
484 $fbuid = $this->flink->foreign_id;
488 "Attempting to post notice %d as a status update for %s (%d), fbuid %s",
490 $this->user->nickname,
497 $result = $this->facebook->api(
499 'method' => 'users.setStatus',
500 'status' => $this->formatMessage(),
501 'status_includes_verb' => true,
506 if ($result == 1) { // 1 is success
511 "Posted notice %s as a status update for %s (%d), fbuid %s",
513 $this->user->nickname,
520 // There is no item ID returned for status update so we can't
521 // save a Notice_to_item mapping
526 "Error posting notice %s as a status update for %s (%d), fbuid %s - error code: %s",
528 $this->user->nickname,
531 $result // will contain 0, or an error
534 throw new FacebookApiException($msg, $result);
539 * Publish a notice to a Facebook user's stream using the old REST API
541 function restPublishStream()
543 $fbuid = $this->flink->foreign_id;
547 'Attempting to post notice %d as stream item for %s (%d) fbuid %s',
549 $this->user->nickname,
556 $fbattachment = $this->formatAttachments();
558 $result = $this->facebook->api(
560 'method' => 'stream.publish',
561 'message' => $this->formatMessage(),
562 'attachment' => $fbattachment,
567 if (!empty($result)) { // result will contain the item ID
570 Notice_to_item::saveNew($this->notice->id, $result);
575 'Posted notice %d as a %s for %s (%d), fbuid %s',
577 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
578 $this->user->nickname,
588 'Could not post notice %d as a %s for %s (%d), fbuid %s - error code: %s',
590 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
591 $this->user->nickname,
593 $result, // result will contain an error code
597 throw new FacebookApiException($msg, $result);
602 * Format the text message of a stream item so it's appropriate for
603 * sending to Facebook. If the notice is too long, truncate it, and
604 * add a linkback to the original notice at the end.
606 * @return String $txt the formated message
608 function formatMessage()
610 // Start with the plaintext source of this notice...
611 $txt = $this->notice->content;
613 // Facebook has a 420-char hardcoded max.
614 if (mb_strlen($statustxt) > 420) {
615 $noticeUrl = common_shorten_url($this->notice->uri);
616 $urlLen = mb_strlen($noticeUrl);
617 $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' … ' . $noticeUrl;
624 * Format attachments for the old REST API stream.publish method
626 * Note: Old REST API supports multiple attachments per post
629 function formatAttachments()
631 $attachments = $this->notice->attachments();
633 $fbattachment = array();
634 $fbattachment['media'] = array();
636 foreach($attachments as $attachment)
638 if($enclosure = $attachment->getEnclosure()){
639 $fbmedia = $this->getFacebookMedia($enclosure);
641 $fbmedia = $this->getFacebookMedia($attachment);
644 $fbattachment['media'][]=$fbmedia;
646 $fbattachment['name'] = ($attachment->title ?
647 $attachment->title : $attachment->url);
648 $fbattachment['href'] = $attachment->url;
651 if(count($fbattachment['media'])>0){
652 unset($fbattachment['name']);
653 unset($fbattachment['href']);
655 return $fbattachment;
659 * given a File objects, returns an associative array suitable for Facebook media
661 function getFacebookMedia($attachment)
665 if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
666 $fbmedia['type'] = 'image';
667 $fbmedia['src'] = $attachment->url;
668 $fbmedia['href'] = $attachment->url;
669 } else if ($attachment->mimetype == 'audio/mpeg') {
670 $fbmedia['type'] = 'mp3';
671 $fbmedia['src'] = $attachment->url;
672 }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
673 $fbmedia['type'] = 'flash';
675 // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
676 // says that imgsrc is required... but we have no value to put in it
677 // $fbmedia['imgsrc']='';
679 $fbmedia['swfsrc'] = $attachment->url;
687 * Disconnect a user from Facebook by deleting his Foreign_link.
688 * Notifies the user his account has been disconnected by email.
690 function disconnect()
692 $fbuid = $this->flink->foreign_id;
697 'Removing Facebook link for %s (%d), fbuid %s',
698 $this->user->nickname,
705 $result = $this->flink->delete();
707 if (empty($result)) {
711 'Could not remove Facebook link for %s (%d), fbuid %s',
712 $this->user->nickname,
718 common_log_db_error($flink, 'DELETE', __FILE__);
721 // Notify the user that we are removing their Facebook link
723 $result = $this->mailFacebookDisconnect();
727 $msg = 'Unable to send email to notify %s (%d), fbuid %s '
728 . 'about his/her Facebook link being removed.';
734 $this->user->nickname,
744 * Send a mail message to notify a user that her Facebook link
745 * has been terminated.
747 * @return boolean success flag
749 function mailFacebookDisconnect()
751 $profile = $this->user->getProfile();
753 $siteName = common_config('site', 'name');
755 common_switch_locale($this->user->language);
757 $subject = _m('Your Facebook connection has been removed');
762 We're sorry to inform you we are unable to publish your notice to
763 Facebook, and have removed the connection between your %2$s account and
766 This may have happened because you have removed permission for %2$s
767 to post on your behalf, or perhaps you have deactivated your Facebook
768 account. You can reconnect your %s account to Facebook at any time by
769 logging in with Facebook again.
777 $this->user->nickname,
781 common_switch_locale();
783 return mail_to_user($this->user, $subject, $body);
787 * Check to see if we have a mapping to a copy of this notice
790 * @param Notice $notice the notice to check
792 * @return mixed null if it can't find one, or the id of the Facebook
795 static function facebookStatusId($notice)
797 $n2i = Notice_to_item::staticGet('notice_id', $notice->id);
802 return $n2i->item_id;
807 * Save a Foreign_user record of a Facebook user
809 * @param object $fbuser a Facebook Graph API user obj
810 * See: http://developers.facebook.com/docs/reference/api/user
811 * @return mixed $result Id or key
814 static function addFacebookUser($fbuser)
816 // remove any existing, possibly outdated, record
817 $luser = Foreign_user::getForeignUser($fbuser['id'], FACEBOOK_SERVICE);
819 if (!empty($luser)) {
821 $result = $luser->delete();
823 if ($result != false) {
827 'Removed old Facebook user: %s, fbuid %d',
836 $fuser = new Foreign_user();
838 $fuser->nickname = $fbuser['name'];
839 $fuser->uri = $fbuser['link'];
840 $fuser->id = $fbuser['id'];
841 $fuser->service = FACEBOOK_SERVICE;
842 $fuser->created = common_sql_now();
844 $result = $fuser->insert();
846 if (empty($result)) {
850 'Failed to add new Facebook user: %s, fbuid %d',
857 common_log_db_error($fuser, 'INSERT', __FILE__);
862 'Added new Facebook user: %s, fbuid %d',
874 * Remove an item from a Facebook user's feed if we have a mapping
877 function streamRemove()
879 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
881 if (!empty($this->flink) && !empty($n2i)) {
883 $result = $this->facebook->api(
885 'method' => 'stream.remove',
886 'post_id' => $n2i->item_id,
887 'uid' => $this->flink->foreign_id
891 if (!empty($result) && result == true) {
896 'Deleted Facebook item: %s for %s (%d), fbuid %d',
898 $this->user->nickname,
900 $this->flink->foreign_id
912 'Could not deleted Facebook item: %s for %s (%d), fbuid %d',
914 $this->user->nickname,
916 $this->flink->foreign_id
925 * Like an item in a Facebook user's feed if we have a mapping
930 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
932 if (!empty($this->flink) && !empty($n2i)) {
934 $result = $this->facebook->api(
936 'method' => 'stream.addlike',
937 'post_id' => $n2i->item_id,
938 'uid' => $this->flink->foreign_id
942 if (!empty($result) && result == true) {
947 'Added like for item: %s for %s (%d), fbuid %d',
949 $this->user->nickname,
951 $this->flink->foreign_id
961 'Could not like Facebook item: %s for %s (%d), fbuid %d',
963 $this->user->nickname,
965 $this->flink->foreign_id
974 * Unlike an item in a Facebook user's feed if we have a mapping
979 $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
981 if (!empty($this->flink) && !empty($n2i)) {
983 $result = $this->facebook->api(
985 'method' => 'stream.removeLike',
986 'post_id' => $n2i->item_id,
987 'uid' => $this->flink->foreign_id
991 if (!empty($result) && result == true) {
996 'Removed like for item: %s for %s (%d), fbuid %d',
998 $this->user->nickname,
1000 $this->flink->foreign_id
1010 'Could not remove like for Facebook item: %s for %s (%d), fbuid %d',
1012 $this->user->nickname,
1014 $this->flink->foreign_id