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
50 //protected $oldRestClient = null; // Old REST API client
52 function __construct($notice)
54 $this->facebook = self::getFacebook();
55 $this->notice = $notice;
57 $this->flink = Foreign_link::getByUserID(
62 $this->user = $this->flink->getUser();
66 * Get an instance of the Facebook Graph SDK object
68 * @param string $appId Application
69 * @param string $secret Facebook API secret
71 * @return Facebook A Facebook SDK obj
73 static function getFacebook($appId = null, $secret = null)
75 // Check defaults and configuration for application ID and secret
77 $appId = common_config('facebook', 'appid');
81 $secret = common_config('facebook', 'secret');
84 // If there's no app ID and secret set in the local config, look
86 if (empty($appId) || empty($secret)) {
87 $appId = common_config('facebook', 'global_appid');
88 $secret = common_config('facebook', 'global_secret');
101 * Broadcast a notice to Facebook
103 * @param Notice $notice the notice to send
105 static function facebookBroadcastNotice($notice)
107 common_debug('Facebook broadcast');
108 $client = new Facebookclient($notice);
109 return $client->sendNotice();
113 * Should the notice go to Facebook?
115 function isFacebookBound() {
117 if (empty($this->flink)) {
121 "No Foreign_link to Facebook for the author of notice %d.",
130 if ($this->notice->source == 'Facebook') {
134 'Skipping notice %d because its source is Facebook.',
142 // If the user does not want to broadcast to Facebook, move along
143 if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
147 'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
155 // If it's not a reply, or if the user WANTS to send @-replies,
156 // then, yeah, it can go to Facebook.
157 if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $this->notice->content) ||
158 ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
166 * Determine whether we should send this notice using the Graph API or the
167 * old REST API and then dispatch
169 function sendNotice()
171 // If there's nothing in the credentials field try to send via
174 if ($this->isFacebookBound()) {
175 common_debug("notice is facebook bound", __FILE__);
176 if (empty($this->flink->credentials)) {
177 $this->sendOldRest();
180 // Otherwise we most likely have an access token
187 "Skipping notice %d - not bound for Facebook",
196 * Send a notice to Facebook using the Graph API
202 $fbuid = $this->flink->foreign_id;
206 "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %s",
208 $this->user->nickname,
216 'access_token' => $this->flink->credentials,
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
244 } catch (FacebookApiException $e) {
245 return $this->handleFacebookError($e);
252 * Send a notice to Facebook using the deprecated Old REST API. We need this
253 * for backwards compatibility. Users who signed up for Facebook bridging
254 * using the old Facebook Canvas application do not have an OAuth 2.0
257 function sendOldRest()
261 $canPublish = $this->checkPermission('publish_stream');
262 $canUpdate = $this->checkPermission('status_update');
264 // We prefer to use stream.publish, because it can handle
265 // attachments and returns the ID of the published item
267 if ($canPublish == 1) {
268 $this->restPublishStream();
269 } else if ($canUpdate == 1) {
270 // as a last resort we can just update the user's "status"
271 $this->restStatusUpdate();
274 $msg = 'Not sending notice %d to Facebook because user %s '
275 . '(%d), fbuid %s, does not have \'status_update\' '
276 . 'or \'publish_stream\' permission.';
283 $this->user->nickname,
285 $this->flink->foreign_id
291 } catch (FacebookApiException $e) {
292 return $this->handleFacebookError($e);
299 * Query Facebook to to see if a user has permission
303 * @param $permission the permission to check for - must be either
304 * public_stream or status_update
306 * @return boolean result
308 function checkPermission($permission)
310 if (!in_array($permission, array('publish_stream', 'status_update'))) {
311 throw new ServerException("No such permission!");
314 $fbuid = $this->flink->foreign_id;
318 'Checking for %s permission for user %s (%d), fbuid %s',
320 $this->user->nickname,
327 $hasPermission = $this->facebook->api(
329 'method' => 'users.hasAppPermission',
330 'ext_perm' => $permission,
335 if ($hasPermission == 1) {
339 '%s (%d), fbuid %s has %s permission',
341 $this->user->nickname,
352 $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
353 . 'Facebook returned: %s';
358 $this->user->nickname,
362 var_export($result, true)
373 * Handle a Facebook API Exception
375 * @param FacebookApiException $e the exception
378 function handleFacebookError($e)
380 $fbuid = $this->flink->foreign_id;
381 $errmsg = $e->getMessage();
382 $code = $e->getCode();
384 // The Facebook PHP SDK seems to always set the code attribute
385 // of the Exception to 0; they put the real error code it in
388 preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
389 $code = $matches['code'];
392 // XXX: Check for any others?
394 case 100: // Invalid parameter
395 $msg = 'Facebook claims notice %d was posted with an invalid '
396 . 'parameter (error code 100 - %s) Notice details: '
397 . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
404 $this->user->nickname,
407 $this->notice->content
413 case 200: // Permissions error
414 case 250: // Updating status requires the extended permission status_update
416 return true; // dequeue
418 case 341: // Feed action request limit reached
419 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
420 . 'for posting notices to Facebook today. Dequeuing '
432 // @fixme: We want to rety at a later time when the throttling has expired
433 // instead of just giving up.
437 $msg = 'Facebook returned an error we don\'t know how to deal with '
438 . 'when posting notice %d. Error code: %d, error message: "%s"'
439 . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
440 . 'notice content="%s"]. Dequeing.';
447 $this->user->nickname,
450 $this->notice->content
454 return true; // dequeue
460 * Publish a notice to Facebook as a status update
462 * This is the least preferable way to send a notice to Facebook because
463 * it doesn't support attachments and the API method doesn't return
464 * the ID of the post on Facebook.
467 function restStatusUpdate()
469 $fbuid = $this->flink->foreign_id;
473 "Attempting to post notice %d as a status update for %s (%d), fbuid %s",
475 $this->user->nickname,
482 $result = $this->facebook->api(
484 'method' => 'users.setStatus',
485 'status' => $this->notice->content,
486 'status_includes_verb' => true,
494 "Posted notice %s as a status update for %s (%d), fbuid %s",
496 $this->user->nickname,
506 * Publish a notice to a Facebook user's stream using the old REST API
508 function restPublishStream()
510 $fbuid = $this->flink->foreign_id;
514 'Attempting to post notice %d as stream item for %s (%d) fbuid %s',
516 $this->user->nickname,
523 $fbattachment = $this->formatAttachments();
525 $result = $this->facebook->api(
527 'method' => 'stream.publish',
528 'message' => $this->notice->content,
529 'attachment' => $fbattachment,
537 'Posted notice %d as a %s for %s (%d), fbuid %s',
539 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
540 $this->user->nickname,
550 * Format attachments for the old REST API stream.publish method
552 * Note: Old REST API supports multiple attachments per post
555 function formatAttachments()
558 $attachments = $this->notice->attachments();
560 $fbattachment = array();
561 $fbattachment['media'] = array();
563 foreach($attachments as $attachment)
565 if($enclosure = $attachment->getEnclosure()){
566 $fbmedia = $this->getFacebookMedia($enclosure);
568 $fbmedia = $this->getFacebookMedia($attachment);
571 $fbattachment['media'][]=$fbmedia;
573 $fbattachment['name'] = ($attachment->title ?
574 $attachment->title : $attachment->url);
575 $fbattachment['href'] = $attachment->url;
578 if(count($fbattachment['media'])>0){
579 unset($fbattachment['name']);
580 unset($fbattachment['href']);
582 return $fbattachment;
586 * given a File objects, returns an associative array suitable for Facebook media
588 function getFacebookMedia($attachment)
592 if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
593 $fbmedia['type'] = 'image';
594 $fbmedia['src'] = $attachment->url;
595 $fbmedia['href'] = $attachment->url;
596 } else if ($attachment->mimetype == 'audio/mpeg') {
597 $fbmedia['type'] = 'mp3';
598 $fbmedia['src'] = $attachment->url;
599 }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
600 $fbmedia['type'] = 'flash';
602 // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
603 // says that imgsrc is required... but we have no value to put in it
604 // $fbmedia['imgsrc']='';
606 $fbmedia['swfsrc'] = $attachment->url;
614 * Disconnect a user from Facebook by deleting his Foreign_link.
615 * Notifies the user his account has been disconnected by email.
617 function disconnect()
619 $fbuid = $this->flink->foreign_id;
624 'Removing Facebook link for %s (%d), fbuid %s',
625 $this->user->nickname,
632 $result = $this->flink->delete();
634 if (empty($result)) {
638 'Could not remove Facebook link for %s (%d), fbuid %s',
639 $this->user->nickname,
645 common_log_db_error($flink, 'DELETE', __FILE__);
648 // Notify the user that we are removing their Facebook link
650 $result = $this->mailFacebookDisconnect();
654 $msg = 'Unable to send email to notify %s (%d), fbuid %s '
655 . 'about his/her Facebook link being removed.';
661 $this->user->nickname,
671 * Send a mail message to notify a user that her Facebook link
672 * has been terminated.
674 * @return boolean success flag
676 function mailFacebookDisconnect()
678 $profile = $user->getProfile();
680 $siteName = common_config('site', 'name');
682 common_switch_locale($user->language);
685 _m('Your Facebook connection has been removed'),
690 Hi, %1$s. We're sorry to inform you we are unable to publish your notice to
691 Facebook, and have removed the connection between your %2$s account and Facebook.
693 This may have happened because you have removed permission for %2$s to post on
694 your behalf, or perhaps you have deactivated your Facebook account. You can
695 reconnect your %s account to Facebook at any time by logging in with Facebook
700 $this->user->nickname,
704 common_switch_locale();
706 return mail_to_user($this->user, $subject, $body);