3 * Name: Facebook Post Connector
5 * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
6 * Author: Tobias Hößl <https://github.com/CatoTH/>
12 * Installing the Friendica/Facebook connector
14 * Detailed instructions how to use this plugin can be found at
15 * https://github.com/friendica/friendica/wiki/How-to:-Friendica%E2%80%99s-Facebook-connector
17 * Vidoes and embeds will not be posted if there is no other content. Links
18 * and images will be converted to a format suitable for the Facebook API and
19 * long posts truncated - with a link to view the full post.
21 * Facebook contacts will not be able to view private photos, as they are not able to
22 * authenticate to your site to establish identity. We will address this
23 * in a future release.
26 define('FACEBOOK_DEFAULT_POLL_INTERVAL', 5); // given in minutes
28 require_once('include/security.php');
30 function fbpost_install() {
31 register_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
32 register_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
33 register_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
34 register_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
35 register_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
36 register_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
37 register_hook('cron', 'addon/fbpost/fbpost.php', 'fbpost_cron');
38 register_hook('prepare_body', 'addon/fbpost/fbpost.php', 'fbpost_prepare_body');
42 function fbpost_uninstall() {
43 unregister_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
44 unregister_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
45 unregister_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
46 unregister_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
47 unregister_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
48 unregister_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
49 unregister_hook('cron', 'addon/fbpost/fbpost.php', 'fbpost_cron');
50 unregister_hook('prepare_body', 'addon/fbpost/fbpost.php', 'fbpost_prepare_body');
54 /* declare the fbpost_module function so that /fbpost url requests will land here */
56 function fbpost_module() {}
60 // If a->argv[1] is a nickname, this is a callback from Facebook oauth requests.
61 // If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API
66 function fbpost_init(&$a) {
74 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
77 if(!(isset($r) && count($r)))
81 $auth_code = (x($_GET, 'code') ? $_GET['code'] : '');
82 $error = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
86 logger('fbpost_init: Error: ' . $error);
88 if($auth_code && $uid) {
90 $appid = get_config('facebook','appid');
91 $appsecret = get_config('facebook', 'appsecret');
93 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
94 . $appid . '&client_secret=' . $appsecret . '&redirect_uri='
95 . urlencode($a->get_baseurl() . '/fbpost/' . $nick)
96 . '&code=' . $auth_code);
98 logger('fbpost_init: returned access token: ' . $x, LOGGER_DATA);
100 if(strpos($x,'access_token=') !== false) {
101 $token = str_replace('access_token=', '', $x);
102 if(strpos($token,'&') !== false)
103 $token = substr($token,0,strpos($token,'&'));
104 set_pconfig($uid,'facebook','access_token',$token);
105 set_pconfig($uid,'facebook','post','1');
106 fbpost_get_self($uid);
117 function fbpost_get_self($uid) {
118 $access_token = get_pconfig($uid,'facebook','access_token');
121 $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
123 $j = json_decode($s);
124 set_pconfig($uid,'facebook','self_id',(string) $j->id);
129 // This is the POST method to the facebook settings page
130 // Content is posted to Facebook in the function facebook_post_hook()
135 function fbpost_post(&$a) {
140 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
141 set_pconfig($uid,'facebook','post_by_default', $value);
143 $value = ((x($_POST,'mirror_posts')) ? intval($_POST['mirror_posts']) : 0);
144 set_pconfig($uid,'facebook','mirror_posts', $value);
147 del_pconfig($uid,'facebook','last_created');
149 $value = ((x($_POST,'suppress_view_on_friendica')) ? intval($_POST['suppress_view_on_friendica']) : 0);
150 set_pconfig($uid,'facebook','suppress_view_on_friendica', $value);
152 $value = ((x($_POST,'post_to_page')) ? $_POST['post_to_page'] : "0-0");
153 $values = explode("-", $value);
154 set_pconfig($uid,'facebook','post_to_page', $values[0]);
155 set_pconfig($uid,'facebook','page_access_token', $values[1]);
157 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
158 if (count($result) > 0) {
159 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
160 set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
163 info( t('Settings updated.') . EOL);
169 // Facebook settings form
175 function fbpost_content(&$a) {
178 notice( t('Permission denied.') . EOL);
183 if(! service_class_allows(local_user(),'facebook_connect')) {
184 notice( t('Permission denied.') . EOL);
185 return upgrade_bool_message();
189 if($a->argc > 1 && $a->argv[1] === 'remove') {
190 del_pconfig(local_user(),'facebook','post');
191 info( t('Facebook Post disabled') . EOL);
194 require_once("mod/settings.php");
200 $fb_installed = false;
201 if (get_pconfig(local_user(),'facebook','post')) {
202 $access_token = get_pconfig(local_user(),'facebook','access_token');
204 // fetching the list of accounts to check, if facebook is working
205 // The value is needed several lines below.
206 $url = 'https://graph.facebook.com/me/accounts';
207 $s = fetch_url($url."?access_token=".$access_token, false, $redirects, 10);
209 $accounts = json_decode($s);
210 if (isset($accounts->data))
211 $fb_installed = true;
214 // I'm not totally sure, if this above will work in every situation,
215 // So this old code will be called as well.
216 if (!$fb_installed) {
217 $url ="https://graph.facebook.com/me/feed";
218 $s = fetch_url($url."?access_token=".$access_token."&limit=1", false, $redirects, 10);
220 $j = json_decode($s);
222 $fb_installed = true;
228 $appid = get_config('facebook','appid');
231 notice( t('Facebook API key is missing.') . EOL);
235 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
236 . $a->get_baseurl() . '/addon/fbpost/fbpost.css' . '" media="all" />' . "\r\n";
238 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
239 $fbsync = (count($result) > 0);
242 $title = t('Facebook Import/Export/Mirror');
244 $title = t('Facebook Export/Mirror');
246 $o .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'.$title.'</h3>';
248 if(! $fb_installed) {
249 $o .= '<div id="fbpost-enable-wrapper">';
251 //read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access
252 //export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,share_item,video_upload,status_update
254 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
255 . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=publish_actions,publish_pages,user_posts,user_photos,user_status,user_videos,manage_pages,user_managed_groups">' . t('Install Facebook Post connector for this account.') . '</a>';
260 $o .= '<div id="fbpost-disable-wrapper">';
262 $o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
264 $o .= '<div id="fbpost-enable-wrapper">';
266 //export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,share_item,video_upload,status_update
268 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
269 . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=publish_actions,publish_pages,user_posts,user_photos,user_status,user_videos,manage_pages,user_managed_groups">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
272 $o .= '<div id="fbpost-post-default-form">';
273 $o .= '<form action="fbpost" method="post" >';
274 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
275 $checked = (($post_by_default) ? ' checked="checked" ' : '');
276 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
278 $suppress_view_on_friendica = get_pconfig(local_user(),'facebook','suppress_view_on_friendica');
279 $checked = (($suppress_view_on_friendica) ? ' checked="checked" ' : '');
280 $o .= '<input type="checkbox" name="suppress_view_on_friendica" value="1"' . $checked . '/>' . ' ' . t('Suppress "View on friendica"') . EOL;
282 $mirror_posts = get_pconfig(local_user(),'facebook','mirror_posts');
283 $checked = (($mirror_posts) ? ' checked="checked" ' : '');
284 $o .= '<input type="checkbox" name="mirror_posts" value="1"' . $checked . '/>' . ' ' . t('Mirror wall posts from facebook to friendica.') . EOL;
287 $post_to_page = get_pconfig(local_user(),'facebook','post_to_page');
288 $page_access_token = get_pconfig(local_user(),'facebook','page_access_token');
289 $fb_token = get_pconfig($a->user['uid'],'facebook','access_token');
290 //$url = 'https://graph.facebook.com/me/accounts';
291 //$x = fetch_url($url."?access_token=".$fb_token, false, $redirects, 10);
292 //$accounts = json_decode($x);
294 $o .= t("Post to page/group:")."<select name='post_to_page'>";
295 if (intval($post_to_page) == 0)
296 $o .= "<option value='0-0' selected>".t('None')."</option>";
298 $o .= "<option value='0-0'>".t('None')."</option>";
300 foreach($accounts->data as $account) {
301 if (is_array($account->perms))
302 if ($post_to_page == $account->id)
303 $o .= "<option value='".$account->id."-".$account->access_token."' selected>".$account->name."</option>";
305 $o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
308 $url = 'https://graph.facebook.com/me/groups';
309 $x = fetch_url($url."?access_token=".$fb_token, false, $redirects, 10);
310 $groups = json_decode($x);
312 foreach($groups->data as $group) {
313 if ($post_to_page == $group->id)
314 $o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
316 $o .= "<option value='".$group->id."-0'>".$group->name."</option>";
323 $o .= '<div class="clear"></div>';
325 $sync_enabled = get_pconfig(local_user(),'fbsync','sync');
326 $checked = (($sync_enabled) ? ' checked="checked" ' : '');
327 $o .= '<input type="checkbox" name="fbsync" value="1"' . $checked . '/>' . ' ' . t('Import Facebook newsfeed.') . EOL;
329 $create_user = get_pconfig(local_user(),'fbsync','create_user');
330 $checked = (($create_user) ? ' checked="checked" ' : '');
331 $o .= '<input type="checkbox" name="create_user" value="1"' . $checked . '/>' . ' ' . t('Automatically create contacts.') . EOL;
334 $o .= '<p><input type="submit" name="submit" value="' . t('Save Settings') . '" /></form></div>';
342 * @param null|object $b
344 function fbpost_plugin_settings(&$a,&$b) {
346 $enabled = get_pconfig(local_user(),'facebook','post');
347 $css = (($enabled) ? '' : '-disabled');
349 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
350 if(count($result) > 0)
351 $title = t('Facebook Import/Export/Mirror');
353 $title = t('Facebook Export/Mirror');
355 $b .= '<div class="settings-block">';
356 $b .= '<a href="fbpost"><img class="connector'.$css.'" src="images/facebook.png" /><h3 class="connector">'.$title.'</h3></a>';
363 * @param null|object $o
365 function fbpost_plugin_admin(&$a, &$o){
368 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
370 $o .= '<h4>' . t('Facebook API Key') . '</h4>';
372 $appid = get_config('facebook', 'appid' );
373 $appsecret = get_config('facebook', 'appsecret' );
375 $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
376 $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
377 if ((count($ret1) > 0 && $ret1[0]['v'] != $appid) || (count($ret2) > 0 && $ret2[0]['v'] != $appsecret)) $o .= t('Error: it appears that you have specified the App-ID and -Secret in your .htconfig.php file. As long as they are specified there, they cannot be set using this form.<br><br>');
379 $o .= '<label for="fb_appid">' . t('App-ID / API-Key') . '</label><input id="fb_appid" name="appid" type="text" value="' . escape_tags($appid ? $appid : "") . '"><br style="clear: both;">';
380 $o .= '<label for="fb_appsecret">' . t('Application secret') . '</label><input id="fb_appsecret" name="appsecret" type="text" value="' . escape_tags($appsecret ? $appsecret : "") . '"><br style="clear: both;">';
382 $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
390 function fbpost_plugin_admin_post(&$a){
391 check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
393 if (x($_REQUEST,'fb_save_keys')) {
394 set_config('facebook', 'appid', $_REQUEST['appid']);
395 set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
397 info(t('The new values have been saved.'));
407 function fbpost_jot_nets(&$a,&$b) {
411 $fb_post = get_pconfig(local_user(),'facebook','post');
412 if(intval($fb_post) == 1) {
413 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
414 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
415 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> '
416 . t('Post to Facebook') . '</div>';
425 function fbpost_post_hook(&$a,&$b) {
427 logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
429 if($b['deleted'] || ($b['created'] !== $b['edited']))
432 logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
434 // if post comes from facebook don't send it back
435 if($b['extid'] == NETWORK_FACEBOOK)
438 if(($b['app'] == "Facebook") AND ($b['verb'] != ACTIVITY_LIKE))
441 logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
444 * Post to Facebook stream
447 require_once('include/group.php');
448 require_once('include/html2plain.php');
455 $allow_arr = array();
457 $toplevel = (($b['id'] == $b['parent']) ? true : false);
460 $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
462 if((!$toplevel) && ($linking)) {
463 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
464 intval($b['parent']),
467 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
468 // dbesc($b['parent-uri']),
472 // is it a reply to a facebook post?
473 // A reply to a toplevel post is only allowed for "real" facebook posts
474 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
475 $reply = substr($r[0]['uri'],4);
476 elseif(count($r) && (substr($r[0]['extid'],0,4) === 'fb::') AND ($r[0]['id'] != $r[0]['parent']))
477 $reply = substr($r[0]['extid'],4);
481 $u = q("SELECT * FROM user where uid = %d limit 1",
487 // only accept comments from the item owner. Other contacts are unknown to FB.
489 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
493 logger('fbpost_post_hook: facebook reply id=' . $reply);
496 if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
498 if($b['private'] && $reply === false) {
499 $allow_people = expand_acl($b['allow_cid']);
500 $allow_groups = expand_groups(expand_acl($b['allow_gid']));
501 $deny_people = expand_acl($b['deny_cid']);
502 $deny_groups = expand_groups(expand_acl($b['deny_gid']));
504 $recipients = array_unique(array_merge($allow_people,$allow_groups));
505 $deny = array_unique(array_merge($deny_people,$deny_groups));
507 $allow_str = dbesc(implode(', ',$recipients));
509 logger("fbpost_post_hook: private post to: ".$allow_str, LOGGER_DEBUG);
510 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
513 $allow_arr[] = $rr['notify'];
516 $deny_str = dbesc(implode(', ',$deny));
518 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
521 $deny_arr[] = $rr['notify'];
524 if(count($deny_arr) && (! count($allow_arr))) {
526 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
527 // This might cause the post to be open to public on Facebook, but only to selected members
528 // on another network. Since this could potentially leak a post to somebody who was denied,
529 // we will skip posting it to Facebook with a slightly vague but relevant message that will
530 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
532 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
537 // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
539 if((! count($allow_arr)) && (! count($deny_arr)))
543 if($b['verb'] == ACTIVITY_LIKE) {
545 logger('fbpost_post_hook: liking '.print_r($b, true), LOGGER_DEBUG);
549 $appid = get_config('facebook', 'appid' );
550 $secret = get_config('facebook', 'appsecret' );
552 if($appid && $secret) {
554 logger('fbpost_post_hook: have appid+secret');
556 $fb_token = get_pconfig($b['uid'],'facebook','access_token');
559 // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
560 // or it's a private message with facebook participants
561 // or it's a reply or likes action to an existing facebook post
563 if($fb_token && ($toplevel || $b['private'] || $reply)) {
564 logger('fbpost_post_hook: able to post');
565 require_once('library/facebook.php');
566 require_once('include/bbcode.php');
570 logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
573 require_once("include/plaintext.php");
574 $msgarr = plaintext($a, $b, 0, false, 9);
575 $msg = $msgarr["text"];
576 $link = $msgarr["url"];
577 $linkname = $msgarr["title"];
579 if ($msgarr["type"] != "video")
580 $image = $msgarr["image"];
582 // Fallback - if message is empty
592 require_once("include/bbcode.php");
593 require_once("include/html2plain.php");
594 $msg = bb_CleanPictureLinks($msg);
595 $msg = bbcode($msg, false, false, 2, true);
596 $msg = trim(html2plain($msg, 0));
602 // If there is nothing to post then exit
606 logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
611 $postvars = array('access_token' => $fb_token);
613 // message, picture, link, name, caption, description, source, place, tags
614 //if(trim($link) != "")
615 // if (@exif_imagetype($link) != 0) {
621 'access_token' => $fb_token,
624 if(trim($image) != "")
625 $postvars['picture'] = $image;
627 if(trim($link) != "") {
628 $postvars['link'] = $link;
630 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
634 if(trim($linkname) != "")
635 $postvars['name'] = $linkname;
638 if(($b['private']) && ($toplevel)) {
639 $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
640 if(count($allow_arr))
641 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
643 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
644 $postvars['privacy'] .= '}';
648 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
649 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
650 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
651 $target = $post_to_page;
656 $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
657 } else if (($video != "") or (($image == "") and ($link != ""))) {
658 // If it is a link to a video or a link without a preview picture then post it as a link
663 'access_token' => $fb_token,
667 $postvars['message'] = $msg;
669 $url = 'https://graph.facebook.com/'.$target.'/links';
670 } else if (($link == "") and ($image != "")) {
671 // If it is only an image without a page link then post this image as a photo
673 'access_token' => $fb_token,
677 $postvars['message'] = $msg;
679 $url = 'https://graph.facebook.com/'.$target.'/photos';
680 //} else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
682 $url = 'https://graph.facebook.com/'.$target.'/feed';
683 if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
684 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
687 // if its only a message and a subject and the message is larger than 500 characters then post it as note
689 'access_token' => $fb_token,
690 'message' => bbcode($b['body'], false, false),
691 'subject' => $b['title'],
693 $url = 'https://graph.facebook.com/'.$target.'/notes';
697 if (!$reply and ($target != "me") and $page_access_token)
698 $postvars['access_token'] = $page_access_token;
700 logger('fbpost_post_hook: post to ' . $url);
701 logger('fbpost_post_hook: postvars: ' . print_r($postvars,true));
703 // "test_mode" prevents anything from actually being posted.
704 // Otherwise, let's do it.
706 if(!get_config('facebook','test_mode')) {
707 $x = post_url($url, $postvars);
708 logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
710 $retj = json_decode($x);
712 // Only set the extid when it isn't the toplevel post
713 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
714 dbesc('fb::' . $retj->id),
719 // Sometimes posts are accepted from facebook although it telling an error
720 // This leads to endless comment flooding.
722 // If it is a special kind of failure the post was receiced
723 // Although facebook said it wasn't received ...
724 if (!$likes AND (($retj->error->type != "OAuthException") OR ($retj->error->code != 2)) AND ($x <> "")) {
725 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
727 $a->contact = $r[0]["id"];
729 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
730 require_once('include/queue_fn.php');
731 add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
732 logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
733 notice( t('Facebook post failed. Queued for retry.') . EOL);
736 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
737 logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
739 $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
740 if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
741 require_once('include/enotify.php');
743 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
746 'type' => NOTIFY_SYSTEM,
747 'system_type' => 'facebook_connection_invalid',
748 'language' => $r[0]['language'],
749 'to_name' => $r[0]['username'],
750 'to_email' => $r[0]['email'],
751 'source_name' => t('Administrator'),
752 'source_link' => $a->config["system"]["url"],
753 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
756 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
757 } else logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
768 * @param object $data
770 function fbpost_enotify(&$app, &$data) {
771 if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
772 $data['itemlink'] = '/fbpost';
773 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
774 $data['subject'] = t('Facebook connection became invalid');
775 $data['body'] = sprintf( t("Hi %1\$s,\n\nThe connection between your accounts on %2\$s and Facebook became invalid. This usually happens after you change your Facebook-password. To enable the connection again, you have to %3\$sre-authenticate the Facebook-connector%4\$s."), $data['params']['to_name'], "[url=" . $app->config["system"]["url"] . "]" . $app->config["sitename"] . "[/url]", "[url=" . $app->config["system"]["url"] . "/fbpost]", "[/url]");
783 function fbpost_post_local(&$a,&$b) {
785 // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
786 // where we will discover it during background delivery.
788 // This can only be triggered by a local user posting to their own wall.
790 if((local_user()) && (local_user() == $b['uid'])) {
792 $fb_post = intval(get_pconfig(local_user(),'facebook','post'));
793 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
795 // if API is used, default to the chosen settings
796 // but allow a specific override
798 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
799 if(! x($_REQUEST,'facebook_enable'))
806 if(strlen($b['postopts']))
807 $b['postopts'] .= ',';
808 $b['postopts'] .= 'facebook';
817 function fbpost_queue_hook(&$a,&$b) {
819 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
820 dbesc(NETWORK_FACEBOOK)
825 require_once('include/queue_fn.php');
828 if($x['network'] !== NETWORK_FACEBOOK)
831 logger('fbpost_queue_hook: run');
833 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
834 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
838 logger('fbpost_queue_hook: no user found for entry '.print_r($x, true));
839 update_queue_time($x['id']);
845 $appid = get_config('facebook', 'appid' );
846 $secret = get_config('facebook', 'appsecret' );
848 if($appid && $secret) {
849 $fb_post = intval(get_pconfig($user['uid'],'facebook','post'));
850 $fb_token = get_pconfig($user['uid'],'facebook','access_token');
852 if($fb_post && $fb_token) {
853 logger('fbpost_queue_hook: able to post');
854 require_once('library/facebook.php');
856 $z = unserialize($x['content']);
858 $j = post_url($z['url'],$z['post']);
860 $retj = json_decode($j);
862 // Only set the extid when it isn't the toplevel post
863 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
864 dbesc('fb::' . $retj->id),
868 logger('fbpost_queue_hook: success: ' . $j);
869 remove_queue_item($x['id']);
871 logger('fbpost_queue_hook: failed: ' . $j);
873 // If it is a special kind of failure the post was receiced
874 // Although facebook said it wasn't received ...
875 $ret = json_decode($j);
876 if (($ret->error->type != "OAuthException") OR ($ret->error->code != 2) AND ($j <> ""))
877 update_queue_time($x['id']);
879 logger('fbpost_queue_hook: Not requeued, since it seems to be received');
882 logger('fbpost_queue_hook: No fb_post or fb_token.');
883 update_queue_time($x['id']);
886 logger('fbpost_queue_hook: No appid or secret.');
887 update_queue_time($x['id']);
894 * @return bool|string
896 function fbpost_get_app_access_token() {
898 $acc_token = get_config('facebook','app_access_token');
900 if ($acc_token !== false) return $acc_token;
902 $appid = get_config('facebook','appid');
903 $appsecret = get_config('facebook', 'appsecret');
905 if ($appid === false || $appsecret === false) {
906 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
909 logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
910 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
912 if(strpos($x,'access_token=') !== false) {
913 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
915 $token = str_replace('access_token=', '', $x);
916 if(strpos($token,'&') !== false)
917 $token = substr($token,0,strpos($token,'&'));
920 logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
923 set_config('facebook','app_access_token',$token);
926 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
931 function fbpost_prepare_body(&$a,&$b) {
932 if ($b["item"]["network"] != NETWORK_FACEBOOK)
936 $msg = $b["item"]["body"];
938 require_once("include/bbcode.php");
939 require_once("include/html2plain.php");
940 $msg = bb_CleanPictureLinks($msg);
941 $msg = bbcode($msg, false, false, 2, true);
942 $msg = trim(html2plain($msg, 0));
944 $b['html'] = nl2br(htmlspecialchars($msg));
948 function fbpost_cron($a,$b) {
949 $last = get_config('facebook','last_poll');
951 $poll_interval = intval(get_config('facebook','poll_interval'));
953 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
956 $next = $last + ($poll_interval * 60);
958 logger('facebook: poll intervall not reached');
962 logger('facebook: cron_start');
964 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
967 logger('facebook: fetching for user '.$rr['uid']);
968 fbpost_fetchwall($a, $rr['uid']);
972 logger('facebook: cron_end');
974 set_config('facebook','last_poll', time());
977 function fbpost_cleanpicture($url) {
978 require_once("include/Photo.php");
980 $urldata = parse_url($url);
981 if (isset($urldata["query"])) {
982 parse_str($urldata["query"], $querydata);
983 if (isset($querydata["url"]) AND (get_photo_info($querydata["url"])))
984 return($querydata["url"]);
989 function fbpost_fetchwall($a, $uid) {
990 require_once("include/oembed.php");
991 require_once("include/network.php");
992 require_once("include/items.php");
993 require_once("mod/item.php");
994 require_once("include/bbcode.php");
996 $access_token = get_pconfig($uid,'facebook','access_token');
997 $post_to_page = get_pconfig($uid,'facebook','post_to_page');
998 $mirror_page = get_pconfig($uid,'facebook','mirror_page');
999 $lastcreated = get_pconfig($uid,'facebook','last_created');
1001 if ((int)$post_to_page == 0)
1002 $post_to_page = "me";
1004 if ((int)$mirror_page != 0)
1005 $post_to_page = $mirror_page;
1007 $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
1009 $first_time = ($lastcreated == "");
1011 if ($lastcreated != "")
1012 $url .= "&since=".urlencode($lastcreated);
1014 $feed = fetch_url($url);
1015 $data = json_decode($feed);
1017 if (!is_array($data->data))
1020 $items = array_reverse($data->data);
1022 foreach ($items as $item) {
1023 if ($item->created_time > $lastcreated)
1024 $lastcreated = $item->created_time;
1029 if ($item->application->id == get_config('facebook','appid'))
1032 if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ((int)$mirror_page == 0))
1034 elseif(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
1036 elseif(!isset($item->privacy))
1039 if (($post_to_page != $item->from->id) AND ((int)$post_to_page != 0))
1042 if (!strstr($item->id, $item->from->id."_") AND isset($item->to) AND ((int)$post_to_page == 0))
1045 $_SESSION["authenticated"] = true;
1046 $_SESSION["uid"] = $uid;
1049 $_REQUEST["type"] = "wall";
1050 $_REQUEST["api_source"] = true;
1051 $_REQUEST["profile_uid"] = $uid;
1052 //$_REQUEST["source"] = "Facebook";
1053 $_REQUEST["source"] = $item->application->name;
1054 $_REQUEST["extid"] = NETWORK_FACEBOOK;
1056 $_REQUEST["title"] = "";
1058 $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
1060 $pagedata = array();
1062 $pagedata["type"] = "";
1064 if(isset($item->name) and isset($item->link)) {
1065 $item->link = original_url($item->link);
1066 $oembed_data = oembed_fetch_url($item->link);
1067 $pagedata["type"] = $oembed_data->type;
1068 $pagedata["url"] = $item->link;
1069 $pagedata["title"] = $item->name;
1070 $content = "[bookmark=".$item->link."]".$item->name."[/bookmark]";
1072 // If a link is not only attached but also added in the body, look if it can be removed in the body.
1073 $removedlink = trim(str_replace($item->link, "", $_REQUEST["body"]));
1075 if (($removedlink == "") OR strstr($_REQUEST["body"], $removedlink))
1076 $_REQUEST["body"] = $removedlink;
1078 } elseif (isset($item->name))
1079 $content .= "[b]".$item->name."[/b]";
1081 $pagedata["text"] = "";
1082 if(isset($item->description) and ($item->type != "photo"))
1083 $pagedata["text"] = $item->description;
1085 if(isset($item->caption) and ($item->type == "photo"))
1086 $pagedata["text"] = $item->caption;
1088 // Only import the picture when the message is no video
1089 // oembed display a picture of the video as well
1090 //if ($item->type != "video") {
1091 //if (($item->type != "video") and ($item->type != "photo")) {
1092 if (($pagedata["type"] == "") OR ($pagedata["type"] == "link")) {
1094 $pagedata["type"] = $item->type;
1096 if (isset($item->picture))
1097 $pagedata["images"][0]["src"] = $item->picture;
1099 if (($pagedata["type"] == "photo") AND isset($item->object_id)) {
1100 logger('fbpost_fetchwall: fetching fbid '.$item->object_id, LOGGER_DEBUG);
1101 $url = "https://graph.facebook.com/".$item->object_id."?access_token=".$access_token;
1102 $feed = fetch_url($url);
1103 $data = json_decode($feed);
1104 if (isset($data->images)) {
1105 $pagedata["images"][0]["src"] = $data->images[0]->source;
1106 logger('got fbid image from images for '.$item->object_id, LOGGER_DEBUG);
1107 } elseif (isset($data->source)) {
1108 $pagedata["images"][0]["src"] = $data->source;
1109 logger('got fbid image from source for '.$item->object_id, LOGGER_DEBUG);
1110 } elseif (isset($data->picture)) {
1111 $pagedata["images"][0]["src"] = $data->picture;
1112 logger('got fbid image from picture for '.$item->object_id, LOGGER_DEBUG);
1116 if(trim($_REQUEST["body"].$content.$pagedata["text"]) == '') {
1117 logger('facebook: empty body 1 '.$item->id.' '.print_r($item, true));
1121 $pagedata["images"][0]["src"] = fbpost_cleanpicture($pagedata["images"][0]["src"]);
1123 if(($pagedata["images"][0]["src"] != "") && isset($item->link)) {
1124 $item->link = original_url($item->link);
1125 $pagedata["url"] = $item->link;
1126 $content .= "\n".'[url='.$item->link.'][img]'.$pagedata["images"][0]["src"].'[/img][/url]';
1128 if ($pagedata["images"][0]["src"] != "")
1129 $content .= "\n".'[img]'.$pagedata["images"][0]["src"].'[/img]';
1130 // if just a link, it may be a wall photo - check
1131 if(isset($item->link))
1132 $content .= fbpost_get_photo($uid,$item->link);
1136 if(trim($_REQUEST["body"].$content.$pagedata["text"]) == '') {
1137 logger('facebook: empty body 2 '.$item->id.' '.print_r($item, true));
1141 if ($pagedata["type"] != "")
1142 $_REQUEST["body"] .= add_page_info_data($pagedata);
1145 $_REQUEST["body"] .= "\n".trim($content);
1147 if ($pagedata["text"])
1148 $_REQUEST["body"] .= "\n[quote]".$pagedata["text"]."[/quote]";
1150 $_REQUEST["body"] = trim($_REQUEST["body"]);
1153 if (isset($item->place)) {
1154 if ($item->place->name or $item->place->location->street or
1155 $item->place->location->city or $item->place->location->country) {
1156 $_REQUEST["location"] = '';
1157 if ($item->place->name)
1158 $_REQUEST["location"] .= $item->place->name;
1159 if ($item->place->location->street)
1160 $_REQUEST["location"] .= " ".$item->place->location->street;
1161 if ($item->place->location->city)
1162 $_REQUEST["location"] .= " ".$item->place->location->city;
1163 if ($item->place->location->country)
1164 $_REQUEST["location"] .= " ".$item->place->location->country;
1166 $_REQUEST["location"] = trim($_REQUEST["location"]);
1168 if ($item->place->location->latitude and $item->place->location->longitude)
1169 $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
1170 .' '.substr($item->place->location->longitude, 0, 8);
1173 if(trim($_REQUEST["body"]) == '') {
1174 logger('facebook: empty body 3 '.$item->id.' '.print_r($item, true));
1178 if(trim(strip_tags(bbcode($_REQUEST["body"], false, false))) == '') {
1179 logger('facebook: empty body 4 '.$item->id.' '.print_r($item, true));
1184 //print_r($_REQUEST);
1185 logger('facebook: posting for user '.$uid);
1189 set_pconfig($uid,'facebook','last_created', $lastcreated);
1192 function fbpost_get_photo($uid,$link) {
1193 $access_token = get_pconfig($uid,'facebook','access_token');
1194 if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1197 $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1199 $photo_id = $match[1];
1203 $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
1204 $j = json_decode($x);
1206 return "\n\n".'[url='.$link.'][img]'.$j->picture.'[/img][/url]';
1211 function fpost_cleanpicture($image) {
1213 if ((strpos($image, ".fbcdn.net/") OR strpos($image, "/fbcdn-photos-")) and (substr($image, -6) == "_s.jpg"))
1214 $image = substr($image, 0, -6)."_n.jpg";
1216 $queryvar = fbpost_parse_query($image);
1217 if ($queryvar['url'] != "")
1218 $image = urldecode($queryvar['url']);
1223 function fbpost_parse_query($var) {
1225 * Use this function to parse out the query array element from
1226 * the output of parse_url().
1228 $var = parse_url($var, PHP_URL_QUERY);
1229 $var = html_entity_decode($var);
1230 $var = explode('&', $var);
1233 foreach($var as $val) {
1234 $x = explode('=', $val);
1235 $arr[$x[0]] = $x[1];
1238 unset($val, $x, $var);