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 $this->sendOldRest();
179 // Otherwise we most likely have an access token
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 '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
243 } catch (FacebookApiException $e) {
244 return $this->handleFacebookError($e);
251 * Send a notice to Facebook using the deprecated Old REST API. We need this
252 * for backwards compatibility. Users who signed up for Facebook bridging
253 * using the old Facebook Canvas application do not have an OAuth 2.0
256 function sendOldRest()
260 $canPublish = $this->checkPermission('publish_stream');
261 $canUpdate = $this->checkPermission('status_update');
263 // We prefer to use stream.publish, because it can handle
264 // attachments and returns the ID of the published item
266 if ($canPublish == 1) {
267 $this->restPublishStream();
268 } else if ($canUpdate == 1) {
269 // as a last resort we can just update the user's "status"
270 $this->restStatusUpdate();
273 $msg = 'Not sending notice %d to Facebook because user %s '
274 . '(%d), fbuid %s, does not have \'status_update\' '
275 . 'or \'publish_stream\' permission.';
282 $this->user->nickname,
284 $this->flink->foreign_id
290 } catch (FacebookApiException $e) {
291 return $this->handleFacebookError($e);
298 * Query Facebook to to see if a user has permission
302 * @param $permission the permission to check for - must be either
303 * public_stream or status_update
305 * @return boolean result
307 function checkPermission($permission)
309 if (!in_array($permission, array('publish_stream', 'status_update'))) {
310 throw new ServerException("No such permission!");
313 $fbuid = $this->flink->foreign_id;
317 'Checking for %s permission for user %s (%d), fbuid %s',
319 $this->user->nickname,
326 $hasPermission = $this->facebook->api(
328 'method' => 'users.hasAppPermission',
329 'ext_perm' => $permission,
334 if ($hasPermission == 1) {
338 '%s (%d), fbuid %s has %s permission',
340 $this->user->nickname,
351 $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
352 . 'Facebook returned: %s';
357 $this->user->nickname,
361 var_export($result, true)
372 * Handle a Facebook API Exception
374 * @param FacebookApiException $e the exception
377 function handleFacebookError($e)
379 $fbuid = $this->flink->foreign_id;
380 $errmsg = $e->getMessage();
381 $code = $e->getCode();
383 // The Facebook PHP SDK seems to always set the code attribute
384 // of the Exception to 0; they put the real error code in
387 preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
388 $code = $matches['code'];
391 // XXX: Check for any others?
393 case 100: // Invalid parameter
394 $msg = 'Facebook claims notice %d was posted with an invalid '
395 . 'parameter (error code 100 - %s) Notice details: '
396 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
403 $this->user->nickname,
406 $this->notice->content
412 case 200: // Permissions error
413 case 250: // Updating status requires the extended permission status_update
415 return true; // dequeue
417 case 341: // Feed action request limit reached
418 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
419 . 'for posting notices to Facebook today. Dequeuing '
431 // @fixme: We want to rety at a later time when the throttling has expired
432 // instead of just giving up.
436 $msg = 'Facebook returned an error we don\'t know how to deal with '
437 . 'when posting notice %d. Error code: %d, error message: "%s"'
438 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
439 . 'notice content="%s"]. Dequeing.';
446 $this->user->nickname,
449 $this->notice->content
453 return true; // dequeue
459 * Publish a notice to Facebook as a status update
461 * This is the least preferable way to send a notice to Facebook because
462 * it doesn't support attachments and the API method doesn't return
463 * the ID of the post on Facebook.
466 function restStatusUpdate()
468 $fbuid = $this->flink->foreign_id;
472 "Attempting to post notice %d as a status update for %s (%d), fbuid %s",
474 $this->user->nickname,
481 $result = $this->facebook->api(
483 'method' => 'users.setStatus',
484 'status' => $this->notice->content,
485 'status_includes_verb' => true,
493 "Posted notice %s as a status update for %s (%d), fbuid %s",
495 $this->user->nickname,
505 * Publish a notice to a Facebook user's stream using the old REST API
507 function restPublishStream()
509 $fbuid = $this->flink->foreign_id;
513 'Attempting to post notice %d as stream item for %s (%d) fbuid %s',
515 $this->user->nickname,
522 $fbattachment = $this->formatAttachments();
524 $result = $this->facebook->api(
526 'method' => 'stream.publish',
527 'message' => $this->notice->content,
528 'attachment' => $fbattachment,
536 'Posted notice %d as a %s for %s (%d), fbuid %s',
538 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
539 $this->user->nickname,
549 * Format attachments for the old REST API stream.publish method
551 * Note: Old REST API supports multiple attachments per post
554 function formatAttachments()
556 $attachments = $this->notice->attachments();
558 $fbattachment = array();
559 $fbattachment['media'] = array();
561 foreach($attachments as $attachment)
563 if($enclosure = $attachment->getEnclosure()){
564 $fbmedia = $this->getFacebookMedia($enclosure);
566 $fbmedia = $this->getFacebookMedia($attachment);
569 $fbattachment['media'][]=$fbmedia;
571 $fbattachment['name'] = ($attachment->title ?
572 $attachment->title : $attachment->url);
573 $fbattachment['href'] = $attachment->url;
576 if(count($fbattachment['media'])>0){
577 unset($fbattachment['name']);
578 unset($fbattachment['href']);
580 return $fbattachment;
584 * given a File objects, returns an associative array suitable for Facebook media
586 function getFacebookMedia($attachment)
590 if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
591 $fbmedia['type'] = 'image';
592 $fbmedia['src'] = $attachment->url;
593 $fbmedia['href'] = $attachment->url;
594 } else if ($attachment->mimetype == 'audio/mpeg') {
595 $fbmedia['type'] = 'mp3';
596 $fbmedia['src'] = $attachment->url;
597 }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
598 $fbmedia['type'] = 'flash';
600 // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
601 // says that imgsrc is required... but we have no value to put in it
602 // $fbmedia['imgsrc']='';
604 $fbmedia['swfsrc'] = $attachment->url;
612 * Disconnect a user from Facebook by deleting his Foreign_link.
613 * Notifies the user his account has been disconnected by email.
615 function disconnect()
617 $fbuid = $this->flink->foreign_id;
622 'Removing Facebook link for %s (%d), fbuid %s',
623 $this->user->nickname,
630 $result = $this->flink->delete();
632 if (empty($result)) {
636 'Could not remove Facebook link for %s (%d), fbuid %s',
637 $this->user->nickname,
643 common_log_db_error($flink, 'DELETE', __FILE__);
646 // Notify the user that we are removing their Facebook link
648 $result = $this->mailFacebookDisconnect();
652 $msg = 'Unable to send email to notify %s (%d), fbuid %s '
653 . 'about his/her Facebook link being removed.';
659 $this->user->nickname,
669 * Send a mail message to notify a user that her Facebook link
670 * has been terminated.
672 * @return boolean success flag
674 function mailFacebookDisconnect()
676 $profile = $user->getProfile();
678 $siteName = common_config('site', 'name');
680 common_switch_locale($user->language);
683 _m('Your Facebook connection has been removed'),
688 Hi, %1$s. We're sorry to inform you we are unable to publish your notice to
689 Facebook, and have removed the connection between your %2$s account and Facebook.
691 This may have happened because you have removed permission for %2$s to post on
692 your behalf, or perhaps you have deactivated your Facebook account. You can
693 reconnect your %s account to Facebook at any time by logging in with Facebook
698 $this->user->nickname,
702 common_switch_locale();
704 return mail_to_user($this->user, $subject, $body);