3 * Name: Facebook Post Connector
5 * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
6 * Author: Tobias Hößl <https://github.com/CatoTH/>
11 * Installing the Friendica/Facebook connector
13 * Detailed instructions how to use this plugin can be found at
14 * https://github.com/friendica/friendica/wiki/How-to:-Friendica%E2%80%99s-Facebook-connector
16 * Vidoes and embeds will not be posted if there is no other content. Links
17 * and images will be converted to a format suitable for the Facebook API and
18 * long posts truncated - with a link to view the full post.
20 * Facebook contacts will not be able to view private photos, as they are not able to
21 * authenticate to your site to establish identity. We will address this
22 * in a future release.
25 define('FACEBOOK_DEFAULT_POLL_INTERVAL', 5); // given in minutes
27 require_once('include/security.php');
29 function fbpost_install() {
30 register_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
31 register_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
32 register_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
33 register_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
34 register_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
35 register_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
36 register_hook('cron', 'addon/fbpost/fbpost.php', 'fbpost_cron');
37 register_hook('prepare_body', 'addon/fbpost/fbpost.php', 'fbpost_prepare_body');
41 function fbpost_uninstall() {
42 unregister_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
43 unregister_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
44 unregister_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
45 unregister_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
46 unregister_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
47 unregister_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
48 unregister_hook('cron', 'addon/fbpost/fbpost.php', 'fbpost_cron');
49 unregister_hook('prepare_body', 'addon/fbpost/fbpost.php', 'fbpost_prepare_body');
53 /* declare the fbpost_module function so that /fbpost url requests will land here */
55 function fbpost_module() {}
59 // If a->argv[1] is a nickname, this is a callback from Facebook oauth requests.
60 // If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API
65 function fbpost_init(&$a) {
73 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
76 if(!(isset($r) && count($r)))
80 $auth_code = (x($_GET, 'code') ? $_GET['code'] : '');
81 $error = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
85 logger('fbpost_init: Error: ' . $error);
87 if($auth_code && $uid) {
89 $appid = get_config('facebook','appid');
90 $appsecret = get_config('facebook', 'appsecret');
92 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
93 . $appid . '&client_secret=' . $appsecret . '&redirect_uri='
94 . urlencode($a->get_baseurl() . '/fbpost/' . $nick)
95 . '&code=' . $auth_code);
97 logger('fbpost_init: returned access token: ' . $x, LOGGER_DATA);
99 if(strpos($x,'access_token=') !== false) {
100 $token = str_replace('access_token=', '', $x);
101 if(strpos($token,'&') !== false)
102 $token = substr($token,0,strpos($token,'&'));
103 set_pconfig($uid,'facebook','access_token',$token);
104 set_pconfig($uid,'facebook','post','1');
105 fbpost_get_self($uid);
116 function fbpost_get_self($uid) {
117 $access_token = get_pconfig($uid,'facebook','access_token');
120 $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
122 $j = json_decode($s);
123 set_pconfig($uid,'facebook','self_id',(string) $j->id);
128 // This is the POST method to the facebook settings page
129 // Content is posted to Facebook in the function facebook_post_hook()
134 function fbpost_post(&$a) {
139 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
140 set_pconfig($uid,'facebook','post_by_default', $value);
142 $value = ((x($_POST,'mirror_posts')) ? intval($_POST['mirror_posts']) : 0);
143 set_pconfig($uid,'facebook','mirror_posts', $value);
146 del_pconfig($uid,'facebook','last_created');
148 $value = ((x($_POST,'suppress_view_on_friendica')) ? intval($_POST['suppress_view_on_friendica']) : 0);
149 set_pconfig($uid,'facebook','suppress_view_on_friendica', $value);
151 $value = ((x($_POST,'post_to_page')) ? $_POST['post_to_page'] : "0-0");
152 $values = explode("-", $value);
153 set_pconfig($uid,'facebook','post_to_page', $values[0]);
154 set_pconfig($uid,'facebook','page_access_token', $values[1]);
156 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
157 if (count($result) > 0) {
158 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
159 set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
162 info( t('Settings updated.') . EOL);
168 // Facebook settings form
174 function fbpost_content(&$a) {
177 notice( t('Permission denied.') . EOL);
182 if(! service_class_allows(local_user(),'facebook_connect')) {
183 notice( t('Permission denied.') . EOL);
184 return upgrade_bool_message();
188 if($a->argc > 1 && $a->argv[1] === 'remove') {
189 del_pconfig(local_user(),'facebook','post');
190 info( t('Facebook Post disabled') . EOL);
193 require_once("mod/settings.php");
199 $fb_installed = false;
200 if (get_pconfig(local_user(),'facebook','post')) {
201 $access_token = get_pconfig(local_user(),'facebook','access_token');
203 // fetching the list of accounts to check, if facebook is working
204 // The value is needed several lines below.
205 $url = 'https://graph.facebook.com/me/accounts';
206 $s = fetch_url($url."?access_token=".$access_token, false, $redirects, 10);
208 $accounts = json_decode($s);
209 if (isset($accounts->data))
210 $fb_installed = true;
213 // I'm not totally sure, if this above will work in every situation,
214 // So this old code will be called as well.
215 if (!$fb_installed) {
216 $url ="https://graph.facebook.com/me/feed";
217 $s = fetch_url($url."?access_token=".$access_token."&limit=1", false, $redirects, 10);
219 $j = json_decode($s);
221 $fb_installed = true;
227 $appid = get_config('facebook','appid');
230 notice( t('Facebook API key is missing.') . EOL);
234 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
235 . $a->get_baseurl() . '/addon/fbpost/fbpost.css' . '" media="all" />' . "\r\n";
237 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
238 $fbsync = (count($result) > 0);
241 $title = t('Facebook Import/Export/Mirror');
243 $title = t('Facebook Export/Mirror');
245 $o .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'.$title.'</h3>';
247 if(! $fb_installed) {
248 $o .= '<div id="fbpost-enable-wrapper">';
250 //read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access
252 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
253 . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,share_item,video_upload,status_update">' . t('Install Facebook Post connector for this account.') . '</a>';
258 $o .= '<div id="fbpost-disable-wrapper">';
260 $o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
262 $o .= '<div id="fbpost-enable-wrapper">';
264 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
265 . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,share_item,video_upload,status_update">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
268 $o .= '<div id="fbpost-post-default-form">';
269 $o .= '<form action="fbpost" method="post" >';
270 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
271 $checked = (($post_by_default) ? ' checked="checked" ' : '');
272 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
274 $suppress_view_on_friendica = get_pconfig(local_user(),'facebook','suppress_view_on_friendica');
275 $checked = (($suppress_view_on_friendica) ? ' checked="checked" ' : '');
276 $o .= '<input type="checkbox" name="suppress_view_on_friendica" value="1"' . $checked . '/>' . ' ' . t('Suppress "View on friendica"') . EOL;
278 $mirror_posts = get_pconfig(local_user(),'facebook','mirror_posts');
279 $checked = (($mirror_posts) ? ' checked="checked" ' : '');
280 $o .= '<input type="checkbox" name="mirror_posts" value="1"' . $checked . '/>' . ' ' . t('Mirror wall posts from facebook to friendica.') . EOL;
283 $post_to_page = get_pconfig(local_user(),'facebook','post_to_page');
284 $page_access_token = get_pconfig(local_user(),'facebook','page_access_token');
285 $fb_token = get_pconfig($a->user['uid'],'facebook','access_token');
286 //$url = 'https://graph.facebook.com/me/accounts';
287 //$x = fetch_url($url."?access_token=".$fb_token, false, $redirects, 10);
288 //$accounts = json_decode($x);
290 $o .= t("Post to page/group:")."<select name='post_to_page'>";
291 if (intval($post_to_page) == 0)
292 $o .= "<option value='0-0' selected>".t('None')."</option>";
294 $o .= "<option value='0-0'>".t('None')."</option>";
296 foreach($accounts->data as $account) {
297 if (is_array($account->perms))
298 if ($post_to_page == $account->id)
299 $o .= "<option value='".$account->id."-".$account->access_token."' selected>".$account->name."</option>";
301 $o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
304 $url = 'https://graph.facebook.com/me/groups';
305 $x = fetch_url($url."?access_token=".$fb_token, false, $redirects, 10);
306 $groups = json_decode($x);
308 foreach($groups->data as $group) {
309 if ($post_to_page == $group->id)
310 $o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
312 $o .= "<option value='".$group->id."-0'>".$group->name."</option>";
319 $o .= '<div class="clear"></div>';
321 $sync_enabled = get_pconfig(local_user(),'fbsync','sync');
322 $checked = (($sync_enabled) ? ' checked="checked" ' : '');
323 $o .= '<input type="checkbox" name="fbsync" value="1"' . $checked . '/>' . ' ' . t('Import Facebook newsfeed.') . EOL;
325 $create_user = get_pconfig(local_user(),'fbsync','create_user');
326 $checked = (($create_user) ? ' checked="checked" ' : '');
327 $o .= '<input type="checkbox" name="create_user" value="1"' . $checked . '/>' . ' ' . t('Automatically create contacts.') . EOL;
330 $o .= '<p><input type="submit" name="submit" value="' . t('Save Settings') . '" /></form></div>';
338 * @param null|object $b
340 function fbpost_plugin_settings(&$a,&$b) {
342 $enabled = get_pconfig(local_user(),'facebook','post');
343 $css = (($enabled) ? '' : '-disabled');
345 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
346 if(count($result) > 0)
347 $title = t('Facebook Import/Export/Mirror');
349 $title = t('Facebook Export/Mirror');
351 $b .= '<div class="settings-block">';
352 $b .= '<a href="fbpost"><img class="connector'.$css.'" src="images/facebook.png" /><h3 class="connector">'.$title.'</h3></a>';
359 * @param null|object $o
361 function fbpost_plugin_admin(&$a, &$o){
364 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
366 $o .= '<h4>' . t('Facebook API Key') . '</h4>';
368 $appid = get_config('facebook', 'appid' );
369 $appsecret = get_config('facebook', 'appsecret' );
371 $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
372 $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
373 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>');
375 $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;">';
376 $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;">';
378 $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
386 function fbpost_plugin_admin_post(&$a){
387 check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
389 if (x($_REQUEST,'fb_save_keys')) {
390 set_config('facebook', 'appid', $_REQUEST['appid']);
391 set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
393 info(t('The new values have been saved.'));
403 function fbpost_jot_nets(&$a,&$b) {
407 $fb_post = get_pconfig(local_user(),'facebook','post');
408 if(intval($fb_post) == 1) {
409 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
410 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
411 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> '
412 . t('Post to Facebook') . '</div>';
421 function fbpost_post_hook(&$a,&$b) {
423 logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
425 if($b['deleted'] || ($b['created'] !== $b['edited']))
428 logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
430 // if post comes from facebook don't send it back
431 if($b['extid'] == NETWORK_FACEBOOK)
434 if(($b['app'] == "Facebook") AND ($b['verb'] != ACTIVITY_LIKE))
437 logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
440 * Post to Facebook stream
443 require_once('include/group.php');
444 require_once('include/html2plain.php');
451 $allow_arr = array();
453 $toplevel = (($b['id'] == $b['parent']) ? true : false);
456 $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
458 if((!$toplevel) && ($linking)) {
459 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
460 intval($b['parent']),
463 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
464 // dbesc($b['parent-uri']),
468 // is it a reply to a facebook post?
469 // A reply to a toplevel post is only allowed for "real" facebook posts
470 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
471 $reply = substr($r[0]['uri'],4);
472 elseif(count($r) && (substr($r[0]['extid'],0,4) === 'fb::') AND ($r[0]['id'] != $r[0]['parent']))
473 $reply = substr($r[0]['extid'],4);
477 $u = q("SELECT * FROM user where uid = %d limit 1",
483 // only accept comments from the item owner. Other contacts are unknown to FB.
485 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
489 logger('fbpost_post_hook: facebook reply id=' . $reply);
492 if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
494 if($b['private'] && $reply === false) {
495 $allow_people = expand_acl($b['allow_cid']);
496 $allow_groups = expand_groups(expand_acl($b['allow_gid']));
497 $deny_people = expand_acl($b['deny_cid']);
498 $deny_groups = expand_groups(expand_acl($b['deny_gid']));
500 $recipients = array_unique(array_merge($allow_people,$allow_groups));
501 $deny = array_unique(array_merge($deny_people,$deny_groups));
503 $allow_str = dbesc(implode(', ',$recipients));
505 logger("fbpost_post_hook: private post to: ".$allow_str, LOGGER_DEBUG);
506 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
509 $allow_arr[] = $rr['notify'];
512 $deny_str = dbesc(implode(', ',$deny));
514 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
517 $deny_arr[] = $rr['notify'];
520 if(count($deny_arr) && (! count($allow_arr))) {
522 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
523 // This might cause the post to be open to public on Facebook, but only to selected members
524 // on another network. Since this could potentially leak a post to somebody who was denied,
525 // we will skip posting it to Facebook with a slightly vague but relevant message that will
526 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
528 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
533 // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
535 if((! count($allow_arr)) && (! count($deny_arr)))
539 if($b['verb'] == ACTIVITY_LIKE) {
541 logger('fbpost_post_hook: liking '.print_r($b, true), LOGGER_DEBUG);
545 $appid = get_config('facebook', 'appid' );
546 $secret = get_config('facebook', 'appsecret' );
548 if($appid && $secret) {
550 logger('fbpost_post_hook: have appid+secret');
552 $fb_token = get_pconfig($b['uid'],'facebook','access_token');
555 // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
556 // or it's a private message with facebook participants
557 // or it's a reply or likes action to an existing facebook post
559 if($fb_token && ($toplevel || $b['private'] || $reply)) {
560 logger('fbpost_post_hook: able to post');
561 require_once('library/facebook.php');
562 require_once('include/bbcode.php');
566 logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
569 require_once("include/plaintext.php");
570 $msgarr = plaintext($a, $b, 0, false, 9);
571 $msg = $msgarr["text"];
572 $link = $msgarr["url"];
573 $linkname = $msgarr["title"];
575 if ($msgarr["type"] != "video")
576 $image = $msgarr["image"];
578 // Fallback - if message is empty
588 require_once("include/bbcode.php");
589 require_once("include/html2plain.php");
590 $msg = bb_CleanPictureLinks($msg);
591 $msg = bbcode($msg, false, false, 2, true);
592 $msg = trim(html2plain($msg, 0));
598 // If there is nothing to post then exit
602 logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
607 $postvars = array('access_token' => $fb_token);
609 // message, picture, link, name, caption, description, source, place, tags
610 //if(trim($link) != "")
611 // if (@exif_imagetype($link) != 0) {
617 'access_token' => $fb_token,
620 if(trim($image) != "")
621 $postvars['picture'] = $image;
623 if(trim($link) != "") {
624 $postvars['link'] = $link;
626 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
630 if(trim($linkname) != "")
631 $postvars['name'] = $linkname;
634 if(($b['private']) && ($toplevel)) {
635 $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
636 if(count($allow_arr))
637 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
639 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
640 $postvars['privacy'] .= '}';
644 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
645 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
646 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
647 $target = $post_to_page;
652 $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
653 } else if (($video != "") or (($image == "") and ($link != ""))) {
654 // If it is a link to a video or a link without a preview picture then post it as a link
659 'access_token' => $fb_token,
663 $postvars['message'] = $msg;
665 $url = 'https://graph.facebook.com/'.$target.'/links';
666 } else if (($link == "") and ($image != "")) {
667 // If it is only an image without a page link then post this image as a photo
669 'access_token' => $fb_token,
673 $postvars['message'] = $msg;
675 $url = 'https://graph.facebook.com/'.$target.'/photos';
676 //} else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
678 $url = 'https://graph.facebook.com/'.$target.'/feed';
679 if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
680 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
683 // if its only a message and a subject and the message is larger than 500 characters then post it as note
685 'access_token' => $fb_token,
686 'message' => bbcode($b['body'], false, false),
687 'subject' => $b['title'],
689 $url = 'https://graph.facebook.com/'.$target.'/notes';
693 if (!$reply and ($target != "me") and $page_access_token)
694 $postvars['access_token'] = $page_access_token;
696 logger('fbpost_post_hook: post to ' . $url);
697 logger('fbpost_post_hook: postvars: ' . print_r($postvars,true));
699 // "test_mode" prevents anything from actually being posted.
700 // Otherwise, let's do it.
702 if(!get_config('facebook','test_mode')) {
703 $x = post_url($url, $postvars);
704 logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
706 $retj = json_decode($x);
708 // Only set the extid when it isn't the toplevel post
709 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
710 dbesc('fb::' . $retj->id),
715 // Sometimes posts are accepted from facebook although it telling an error
716 // This leads to endless comment flooding.
718 // If it is a special kind of failure the post was receiced
719 // Although facebook said it wasn't received ...
720 if (!$likes AND (($retj->error->type != "OAuthException") OR ($retj->error->code != 2)) AND ($x <> "")) {
721 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
723 $a->contact = $r[0]["id"];
725 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
726 require_once('include/queue_fn.php');
727 add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
728 logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
729 notice( t('Facebook post failed. Queued for retry.') . EOL);
732 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
733 logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
735 $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
736 if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
737 require_once('include/enotify.php');
739 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
742 'type' => NOTIFY_SYSTEM,
743 'system_type' => 'facebook_connection_invalid',
744 'language' => $r[0]['language'],
745 'to_name' => $r[0]['username'],
746 'to_email' => $r[0]['email'],
747 'source_name' => t('Administrator'),
748 'source_link' => $a->config["system"]["url"],
749 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
752 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
753 } else logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
764 * @param object $data
766 function fbpost_enotify(&$app, &$data) {
767 if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
768 $data['itemlink'] = '/fbpost';
769 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
770 $data['subject'] = t('Facebook connection became invalid');
771 $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]");
779 function fbpost_post_local(&$a,&$b) {
781 // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
782 // where we will discover it during background delivery.
784 // This can only be triggered by a local user posting to their own wall.
786 if((local_user()) && (local_user() == $b['uid'])) {
788 $fb_post = intval(get_pconfig(local_user(),'facebook','post'));
789 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
791 // if API is used, default to the chosen settings
792 // but allow a specific override
794 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
795 if(! x($_REQUEST,'facebook_enable'))
802 if(strlen($b['postopts']))
803 $b['postopts'] .= ',';
804 $b['postopts'] .= 'facebook';
813 function fbpost_queue_hook(&$a,&$b) {
815 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
816 dbesc(NETWORK_FACEBOOK)
821 require_once('include/queue_fn.php');
824 if($x['network'] !== NETWORK_FACEBOOK)
827 logger('fbpost_queue_hook: run');
829 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
830 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
834 logger('fbpost_queue_hook: no user found for entry '.print_r($x, true));
835 update_queue_time($x['id']);
841 $appid = get_config('facebook', 'appid' );
842 $secret = get_config('facebook', 'appsecret' );
844 if($appid && $secret) {
845 $fb_post = intval(get_pconfig($user['uid'],'facebook','post'));
846 $fb_token = get_pconfig($user['uid'],'facebook','access_token');
848 if($fb_post && $fb_token) {
849 logger('fbpost_queue_hook: able to post');
850 require_once('library/facebook.php');
852 $z = unserialize($x['content']);
854 $j = post_url($z['url'],$z['post']);
856 $retj = json_decode($j);
858 // Only set the extid when it isn't the toplevel post
859 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
860 dbesc('fb::' . $retj->id),
864 logger('fbpost_queue_hook: success: ' . $j);
865 remove_queue_item($x['id']);
867 logger('fbpost_queue_hook: failed: ' . $j);
869 // If it is a special kind of failure the post was receiced
870 // Although facebook said it wasn't received ...
871 $ret = json_decode($j);
872 if (($ret->error->type != "OAuthException") OR ($ret->error->code != 2) AND ($j <> ""))
873 update_queue_time($x['id']);
875 logger('fbpost_queue_hook: Not requeued, since it seems to be received');
878 logger('fbpost_queue_hook: No fb_post or fb_token.');
879 update_queue_time($x['id']);
882 logger('fbpost_queue_hook: No appid or secret.');
883 update_queue_time($x['id']);
890 * @return bool|string
892 function fbpost_get_app_access_token() {
894 $acc_token = get_config('facebook','app_access_token');
896 if ($acc_token !== false) return $acc_token;
898 $appid = get_config('facebook','appid');
899 $appsecret = get_config('facebook', 'appsecret');
901 if ($appid === false || $appsecret === false) {
902 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
905 logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
906 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
908 if(strpos($x,'access_token=') !== false) {
909 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
911 $token = str_replace('access_token=', '', $x);
912 if(strpos($token,'&') !== false)
913 $token = substr($token,0,strpos($token,'&'));
916 logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
919 set_config('facebook','app_access_token',$token);
922 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
927 function fbpost_prepare_body(&$a,&$b) {
928 if ($b["item"]["network"] != NETWORK_FACEBOOK)
932 $msg = $b["item"]["body"];
934 require_once("include/bbcode.php");
935 require_once("include/html2plain.php");
936 $msg = bb_CleanPictureLinks($msg);
937 $msg = bbcode($msg, false, false, 2, true);
938 $msg = trim(html2plain($msg, 0));
940 $b['html'] = nl2br(htmlspecialchars($msg));
944 function fbpost_cron($a,$b) {
945 $last = get_config('facebook','last_poll');
947 $poll_interval = intval(get_config('facebook','poll_interval'));
949 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
952 $next = $last + ($poll_interval * 60);
954 logger('facebook: poll intervall not reached');
958 logger('facebook: cron_start');
960 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
963 logger('facebook: fetching for user '.$rr['uid']);
964 fbpost_fetchwall($a, $rr['uid']);
968 logger('facebook: cron_end');
970 set_config('facebook','last_poll', time());
973 function fbpost_cleanpicture($url) {
974 require_once("include/Photo.php");
976 $urldata = parse_url($url);
977 if (isset($urldata["query"])) {
978 parse_str($urldata["query"], $querydata);
979 if (isset($querydata["url"]) AND (get_photo_info($querydata["url"])))
980 return($querydata["url"]);
985 function fbpost_fetchwall($a, $uid) {
986 require_once("include/oembed.php");
987 require_once("include/network.php");
988 require_once("include/items.php");
989 require_once("mod/item.php");
990 require_once("include/bbcode.php");
992 $access_token = get_pconfig($uid,'facebook','access_token');
993 $post_to_page = get_pconfig($uid,'facebook','post_to_page');
994 $mirror_page = get_pconfig($uid,'facebook','mirror_page');
995 $lastcreated = get_pconfig($uid,'facebook','last_created');
997 if ((int)$post_to_page == 0)
998 $post_to_page = "me";
1000 if ((int)$mirror_page != 0)
1001 $post_to_page = $mirror_page;
1003 $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
1005 $first_time = ($lastcreated == "");
1007 if ($lastcreated != "")
1008 $url .= "&since=".urlencode($lastcreated);
1010 $feed = fetch_url($url);
1011 $data = json_decode($feed);
1013 if (!is_array($data->data))
1016 $items = array_reverse($data->data);
1018 foreach ($items as $item) {
1019 if ($item->created_time > $lastcreated)
1020 $lastcreated = $item->created_time;
1025 if ($item->application->id == get_config('facebook','appid'))
1028 //if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
1029 if((isset($item->privacy) && ($item->privacy->value !== 'EVERYONE')) OR !isset($item->privacy))
1032 if (($post_to_page != $item->from->id) AND ((int)$post_to_page != 0))
1035 if (!strstr($item->id, $item->from->id."_") AND isset($item->to) AND ((int)$post_to_page == 0))
1038 $_SESSION["authenticated"] = true;
1039 $_SESSION["uid"] = $uid;
1042 $_REQUEST["type"] = "wall";
1043 $_REQUEST["api_source"] = true;
1044 $_REQUEST["profile_uid"] = $uid;
1045 //$_REQUEST["source"] = "Facebook";
1046 $_REQUEST["source"] = $item->application->name;
1047 $_REQUEST["extid"] = NETWORK_FACEBOOK;
1049 $_REQUEST["title"] = "";
1051 $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
1053 $pagedata = array();
1055 $pagedata["type"] = "";
1057 if(isset($item->name) and isset($item->link)) {
1058 $item->link = original_url($item->link);
1059 $oembed_data = oembed_fetch_url($item->link);
1060 $pagedata["type"] = $oembed_data->type;
1061 $pagedata["url"] = $item->link;
1062 $pagedata["title"] = $item->name;
1063 $content = "[bookmark=".$item->link."]".$item->name."[/bookmark]";
1065 // If a link is not only attached but also added in the body, look if it can be removed in the body.
1066 $removedlink = trim(str_replace($item->link, "", $_REQUEST["body"]));
1068 if (($removedlink == "") OR strstr($_REQUEST["body"], $removedlink))
1069 $_REQUEST["body"] = $removedlink;
1071 } elseif (isset($item->name))
1072 $content .= "[b]".$item->name."[/b]";
1074 $pagedata["text"] = "";
1075 if(isset($item->description) and ($item->type != "photo"))
1076 $pagedata["text"] = $item->description;
1078 if(isset($item->caption) and ($item->type == "photo"))
1079 $pagedata["text"] = $item->caption;
1081 // Only import the picture when the message is no video
1082 // oembed display a picture of the video as well
1083 //if ($item->type != "video") {
1084 //if (($item->type != "video") and ($item->type != "photo")) {
1085 if (($pagedata["type"] == "") OR ($pagedata["type"] == "link")) {
1087 $pagedata["type"] = $item->type;
1089 if (isset($item->picture))
1090 $pagedata["images"][0]["src"] = $item->picture;
1092 if (($pagedata["type"] == "photo") AND isset($item->object_id)) {
1093 logger('fbpost_fetchwall: fetching fbid '.$item->object_id, LOGGER_DEBUG);
1094 $url = "https://graph.facebook.com/".$item->object_id."?access_token=".$access_token;
1095 $feed = fetch_url($url);
1096 $data = json_decode($feed);
1097 if (isset($data->images)) {
1098 $pagedata["images"][0]["src"] = $data->images[0]->source;
1099 logger('got fbid image from images for '.$item->object_id, LOGGER_DEBUG);
1100 } elseif (isset($data->source)) {
1101 $pagedata["images"][0]["src"] = $data->source;
1102 logger('got fbid image from source for '.$item->object_id, LOGGER_DEBUG);
1103 } elseif (isset($data->picture)) {
1104 $pagedata["images"][0]["src"] = $data->picture;
1105 logger('got fbid image from picture for '.$item->object_id, LOGGER_DEBUG);
1109 if(trim($_REQUEST["body"].$content.$pagedata["text"]) == '') {
1110 logger('facebook: empty body 1 '.$item->id.' '.print_r($item, true));
1114 $pagedata["images"][0]["src"] = fbpost_cleanpicture($pagedata["images"][0]["src"]);
1116 if(($pagedata["images"][0]["src"] != "") && isset($item->link)) {
1117 $item->link = original_url($item->link);
1118 $pagedata["url"] = $item->link;
1119 $content .= "\n".'[url='.$item->link.'][img]'.$pagedata["images"][0]["src"].'[/img][/url]';
1121 if ($pagedata["images"][0]["src"] != "")
1122 $content .= "\n".'[img]'.$pagedata["images"][0]["src"].'[/img]';
1123 // if just a link, it may be a wall photo - check
1124 if(isset($item->link))
1125 $content .= fbpost_get_photo($uid,$item->link);
1129 if(trim($_REQUEST["body"].$content.$pagedata["text"]) == '') {
1130 logger('facebook: empty body 2 '.$item->id.' '.print_r($item, true));
1134 if ($pagedata["type"] != "")
1135 $_REQUEST["body"] .= add_page_info_data($pagedata);
1138 $_REQUEST["body"] .= "\n".trim($content);
1140 if ($pagedata["text"])
1141 $_REQUEST["body"] .= "\n[quote]".$pagedata["text"]."[/quote]";
1143 $_REQUEST["body"] = trim($_REQUEST["body"]);
1146 if (isset($item->place)) {
1147 if ($item->place->name or $item->place->location->street or
1148 $item->place->location->city or $item->place->location->country) {
1149 $_REQUEST["location"] = '';
1150 if ($item->place->name)
1151 $_REQUEST["location"] .= $item->place->name;
1152 if ($item->place->location->street)
1153 $_REQUEST["location"] .= " ".$item->place->location->street;
1154 if ($item->place->location->city)
1155 $_REQUEST["location"] .= " ".$item->place->location->city;
1156 if ($item->place->location->country)
1157 $_REQUEST["location"] .= " ".$item->place->location->country;
1159 $_REQUEST["location"] = trim($_REQUEST["location"]);
1161 if ($item->place->location->latitude and $item->place->location->longitude)
1162 $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
1163 .' '.substr($item->place->location->longitude, 0, 8);
1166 if(trim($_REQUEST["body"]) == '') {
1167 logger('facebook: empty body 3 '.$item->id.' '.print_r($item, true));
1171 if(trim(strip_tags(bbcode($_REQUEST["body"], false, false))) == '') {
1172 logger('facebook: empty body 4 '.$item->id.' '.print_r($item, true));
1177 //print_r($_REQUEST);
1178 logger('facebook: posting for user '.$uid);
1182 set_pconfig($uid,'facebook','last_created', $lastcreated);
1185 function fbpost_get_photo($uid,$link) {
1186 $access_token = get_pconfig($uid,'facebook','access_token');
1187 if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1190 $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1192 $photo_id = $match[1];
1196 $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
1197 $j = json_decode($x);
1199 return "\n\n".'[url='.$link.'][img]'.$j->picture.'[/img][/url]';
1204 function fpost_cleanpicture($image) {
1206 if ((strpos($image, ".fbcdn.net/") OR strpos($image, "/fbcdn-photos-")) and (substr($image, -6) == "_s.jpg"))
1207 $image = substr($image, 0, -6)."_n.jpg";
1209 $queryvar = fbpost_parse_query($image);
1210 if ($queryvar['url'] != "")
1211 $image = urldecode($queryvar['url']);
1216 function fbpost_parse_query($var) {
1218 * Use this function to parse out the query array element from
1219 * the output of parse_url().
1221 $var = parse_url($var, PHP_URL_QUERY);
1222 $var = html_entity_decode($var);
1223 $var = explode('&', $var);
1226 foreach($var as $val) {
1227 $x = explode('=', $val);
1228 $arr[$x[0]] = $x[1];
1231 unset($val, $x, $var);