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['app'] == "Facebook") AND ($b['verb'] != ACTIVITY_LIKE))
434 logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
437 * Post to Facebook stream
440 require_once('include/group.php');
441 require_once('include/html2plain.php');
448 $allow_arr = array();
450 $toplevel = (($b['id'] == $b['parent']) ? true : false);
453 $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
455 if((!$toplevel) && ($linking)) {
456 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
457 intval($b['parent']),
460 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
461 // dbesc($b['parent-uri']),
465 // is it a reply to a facebook post?
466 // A reply to a toplevel post is only allowed for "real" facebook posts
467 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
468 $reply = substr($r[0]['uri'],4);
469 elseif(count($r) && (substr($r[0]['extid'],0,4) === 'fb::') AND ($r[0]['id'] != $r[0]['parent']))
470 $reply = substr($r[0]['extid'],4);
474 $u = q("SELECT * FROM user where uid = %d limit 1",
480 // only accept comments from the item owner. Other contacts are unknown to FB.
482 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
486 logger('fbpost_post_hook: facebook reply id=' . $reply);
489 if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
491 if($b['private'] && $reply === false) {
492 $allow_people = expand_acl($b['allow_cid']);
493 $allow_groups = expand_groups(expand_acl($b['allow_gid']));
494 $deny_people = expand_acl($b['deny_cid']);
495 $deny_groups = expand_groups(expand_acl($b['deny_gid']));
497 $recipients = array_unique(array_merge($allow_people,$allow_groups));
498 $deny = array_unique(array_merge($deny_people,$deny_groups));
500 $allow_str = dbesc(implode(', ',$recipients));
502 logger("fbpost_post_hook: private post to: ".$allow_str, LOGGER_DEBUG);
503 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
506 $allow_arr[] = $rr['notify'];
509 $deny_str = dbesc(implode(', ',$deny));
511 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
514 $deny_arr[] = $rr['notify'];
517 if(count($deny_arr) && (! count($allow_arr))) {
519 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
520 // This might cause the post to be open to public on Facebook, but only to selected members
521 // on another network. Since this could potentially leak a post to somebody who was denied,
522 // we will skip posting it to Facebook with a slightly vague but relevant message that will
523 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
525 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
530 // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
532 if((! count($allow_arr)) && (! count($deny_arr)))
536 if($b['verb'] == ACTIVITY_LIKE) {
538 logger('fbpost_post_hook: liking '.print_r($b, true), LOGGER_DEBUG);
542 $appid = get_config('facebook', 'appid' );
543 $secret = get_config('facebook', 'appsecret' );
545 if($appid && $secret) {
547 logger('fbpost_post_hook: have appid+secret');
549 $fb_token = get_pconfig($b['uid'],'facebook','access_token');
552 // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
553 // or it's a private message with facebook participants
554 // or it's a reply or likes action to an existing facebook post
556 if($fb_token && ($toplevel || $b['private'] || $reply)) {
557 logger('fbpost_post_hook: able to post');
558 require_once('library/facebook.php');
559 require_once('include/bbcode.php');
563 logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
566 require_once("include/plaintext.php");
567 $msgarr = plaintext($a, $b, 0, false, 9);
568 $msg = $msgarr["text"];
569 $link = $msgarr["url"];
570 $linkname = $msgarr["title"];
572 if ($msgarr["type"] != "video")
573 $image = $msgarr["image"];
575 // Fallback - if message is empty
585 require_once("include/bbcode.php");
586 require_once("include/html2plain.php");
587 $msg = bb_CleanPictureLinks($msg);
588 $msg = bbcode($msg, false, false, 2, true);
589 $msg = trim(html2plain($msg, 0));
595 // If there is nothing to post then exit
599 logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
604 $postvars = array('access_token' => $fb_token);
606 // message, picture, link, name, caption, description, source, place, tags
607 //if(trim($link) != "")
608 // if (@exif_imagetype($link) != 0) {
614 'access_token' => $fb_token,
617 if(trim($image) != "")
618 $postvars['picture'] = $image;
620 if(trim($link) != "") {
621 $postvars['link'] = $link;
623 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
627 if(trim($linkname) != "")
628 $postvars['name'] = $linkname;
631 if(($b['private']) && ($toplevel)) {
632 $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
633 if(count($allow_arr))
634 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
636 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
637 $postvars['privacy'] .= '}';
641 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
642 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
643 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
644 $target = $post_to_page;
649 $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
650 } else if (($video != "") or (($image == "") and ($link != ""))) {
651 // If it is a link to a video or a link without a preview picture then post it as a link
656 'access_token' => $fb_token,
660 $postvars['message'] = $msg;
662 $url = 'https://graph.facebook.com/'.$target.'/links';
663 } else if (($link == "") and ($image != "")) {
664 // If it is only an image without a page link then post this image as a photo
666 'access_token' => $fb_token,
670 $postvars['message'] = $msg;
672 $url = 'https://graph.facebook.com/'.$target.'/photos';
673 //} else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
675 $url = 'https://graph.facebook.com/'.$target.'/feed';
676 if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
677 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
680 // if its only a message and a subject and the message is larger than 500 characters then post it as note
682 'access_token' => $fb_token,
683 'message' => bbcode($b['body'], false, false),
684 'subject' => $b['title'],
686 $url = 'https://graph.facebook.com/'.$target.'/notes';
690 if (!$reply and ($target != "me") and $page_access_token)
691 $postvars['access_token'] = $page_access_token;
693 logger('fbpost_post_hook: post to ' . $url);
694 logger('fbpost_post_hook: postvars: ' . print_r($postvars,true));
696 // "test_mode" prevents anything from actually being posted.
697 // Otherwise, let's do it.
699 if(!get_config('facebook','test_mode')) {
700 $x = post_url($url, $postvars);
701 logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
703 $retj = json_decode($x);
705 // Only set the extid when it isn't the toplevel post
706 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
707 dbesc('fb::' . $retj->id),
712 // Sometimes posts are accepted from facebook although it telling an error
713 // This leads to endless comment flooding.
715 // If it is a special kind of failure the post was receiced
716 // Although facebook said it wasn't received ...
717 if (!$likes AND (($retj->error->type != "OAuthException") OR ($retj->error->code != 2)) AND ($x <> "")) {
718 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
720 $a->contact = $r[0]["id"];
722 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
723 require_once('include/queue_fn.php');
724 add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
725 logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
726 notice( t('Facebook post failed. Queued for retry.') . EOL);
729 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
730 logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
732 $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
733 if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
734 require_once('include/enotify.php');
736 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
739 'type' => NOTIFY_SYSTEM,
740 'system_type' => 'facebook_connection_invalid',
741 'language' => $r[0]['language'],
742 'to_name' => $r[0]['username'],
743 'to_email' => $r[0]['email'],
744 'source_name' => t('Administrator'),
745 'source_link' => $a->config["system"]["url"],
746 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
749 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
750 } else logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
761 * @param object $data
763 function fbpost_enotify(&$app, &$data) {
764 if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
765 $data['itemlink'] = '/fbpost';
766 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
767 $data['subject'] = t('Facebook connection became invalid');
768 $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]");
776 function fbpost_post_local(&$a,&$b) {
778 // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
779 // where we will discover it during background delivery.
781 // This can only be triggered by a local user posting to their own wall.
783 if((local_user()) && (local_user() == $b['uid'])) {
785 $fb_post = intval(get_pconfig(local_user(),'facebook','post'));
786 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
788 // if API is used, default to the chosen settings
789 // but allow a specific override
791 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
792 if(! x($_REQUEST,'facebook_enable'))
799 if(strlen($b['postopts']))
800 $b['postopts'] .= ',';
801 $b['postopts'] .= 'facebook';
810 function fbpost_queue_hook(&$a,&$b) {
812 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
813 dbesc(NETWORK_FACEBOOK)
818 require_once('include/queue_fn.php');
821 if($x['network'] !== NETWORK_FACEBOOK)
824 logger('fbpost_queue_hook: run');
826 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
827 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
831 logger('fbpost_queue_hook: no user found for entry '.print_r($x, true));
832 update_queue_time($x['id']);
838 $appid = get_config('facebook', 'appid' );
839 $secret = get_config('facebook', 'appsecret' );
841 if($appid && $secret) {
842 $fb_post = intval(get_pconfig($user['uid'],'facebook','post'));
843 $fb_token = get_pconfig($user['uid'],'facebook','access_token');
845 if($fb_post && $fb_token) {
846 logger('fbpost_queue_hook: able to post');
847 require_once('library/facebook.php');
849 $z = unserialize($x['content']);
851 $j = post_url($z['url'],$z['post']);
853 $retj = json_decode($j);
855 // Only set the extid when it isn't the toplevel post
856 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
857 dbesc('fb::' . $retj->id),
861 logger('fbpost_queue_hook: success: ' . $j);
862 remove_queue_item($x['id']);
864 logger('fbpost_queue_hook: failed: ' . $j);
866 // If it is a special kind of failure the post was receiced
867 // Although facebook said it wasn't received ...
868 $ret = json_decode($j);
869 if (($ret->error->type != "OAuthException") OR ($ret->error->code != 2) AND ($j <> ""))
870 update_queue_time($x['id']);
872 logger('fbpost_queue_hook: Not requeued, since it seems to be received');
875 logger('fbpost_queue_hook: No fb_post or fb_token.');
876 update_queue_time($x['id']);
879 logger('fbpost_queue_hook: No appid or secret.');
880 update_queue_time($x['id']);
887 * @return bool|string
889 function fbpost_get_app_access_token() {
891 $acc_token = get_config('facebook','app_access_token');
893 if ($acc_token !== false) return $acc_token;
895 $appid = get_config('facebook','appid');
896 $appsecret = get_config('facebook', 'appsecret');
898 if ($appid === false || $appsecret === false) {
899 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
902 logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
903 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
905 if(strpos($x,'access_token=') !== false) {
906 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
908 $token = str_replace('access_token=', '', $x);
909 if(strpos($token,'&') !== false)
910 $token = substr($token,0,strpos($token,'&'));
913 logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
916 set_config('facebook','app_access_token',$token);
919 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
924 function fbpost_prepare_body(&$a,&$b) {
925 if ($b["item"]["network"] != NETWORK_FACEBOOK)
929 $msg = $b["item"]["body"];
931 require_once("include/bbcode.php");
932 require_once("include/html2plain.php");
933 $msg = bb_CleanPictureLinks($msg);
934 $msg = bbcode($msg, false, false, 2, true);
935 $msg = trim(html2plain($msg, 0));
937 $b['html'] = nl2br(htmlspecialchars($msg));
941 function fbpost_cron($a,$b) {
942 $last = get_config('facebook','last_poll');
944 $poll_interval = intval(get_config('facebook','poll_interval'));
946 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
949 $next = $last + ($poll_interval * 60);
951 logger('facebook: poll intervall not reached');
955 logger('facebook: cron_start');
957 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
960 logger('facebook: fetching for user '.$rr['uid']);
961 fbpost_fetchwall($a, $rr['uid']);
965 logger('facebook: cron_end');
967 set_config('facebook','last_poll', time());
970 function fbpost_cleanpicture($url) {
971 require_once("include/Photo.php");
973 $urldata = parse_url($url);
974 if (isset($urldata["query"])) {
975 parse_str($urldata["query"], $querydata);
976 if (isset($querydata["url"]) AND (get_photo_info($querydata["url"])))
977 return($querydata["url"]);
982 function fbpost_fetchwall($a, $uid) {
983 require_once("include/oembed.php");
984 require_once("include/network.php");
985 require_once('mod/item.php');
987 $access_token = get_pconfig($uid,'facebook','access_token');
988 $post_to_page = get_pconfig($uid,'facebook','post_to_page');
989 $lastcreated = get_pconfig($uid,'facebook','last_created');
991 if ((int)$post_to_page == 0)
992 $post_to_page = "me";
994 $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
996 $first_time = ($lastcreated == "");
998 if ($lastcreated != "")
999 $url .= "&since=".urlencode($lastcreated);
1001 $feed = fetch_url($url);
1002 $data = json_decode($feed);
1004 if (!is_array($data->data))
1007 $items = array_reverse($data->data);
1009 foreach ($items as $item) {
1010 if ($item->created_time > $lastcreated)
1011 $lastcreated = $item->created_time;
1016 if ($item->application->id == get_config('facebook','appid'))
1019 if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
1022 if (($post_to_page != $item->from->id) AND ((int)$post_to_page != 0))
1025 if (!strstr($item->id, $item->from->id."_") AND isset($item->to) AND ((int)$post_to_page == 0))
1028 $_SESSION["authenticated"] = true;
1029 $_SESSION["uid"] = $uid;
1032 $_REQUEST["type"] = "wall";
1033 $_REQUEST["api_source"] = true;
1034 $_REQUEST["profile_uid"] = $uid;
1035 $_REQUEST["source"] = "Facebook";
1037 $_REQUEST["title"] = "";
1039 $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
1044 if(isset($item->name) and isset($item->link)) {
1045 $item->link = original_url($item->link);
1046 $oembed_data = oembed_fetch_url($item->link);
1047 $type = $oembed_data->type;
1048 $content = "[bookmark=".$item->link."]".$item->name."[/bookmark]";
1050 // If a link is not only attached but also added in the body, look if it can be removed in the body.
1051 $removedlink = trim(str_replace($item->link, "", $_REQUEST["body"]));
1053 if (($removedlink == "") OR strstr($_REQUEST["body"], $removedlink))
1054 $_REQUEST["body"] = $removedlink;
1056 } elseif (isset($item->name))
1057 $content .= "[b]".$item->name."[/b]";
1060 if(isset($item->description) and ($item->type != "photo"))
1061 $quote = $item->description;
1063 if(isset($item->caption) and ($item->type == "photo"))
1064 $quote = $item->caption;
1066 // Only import the picture when the message is no video
1067 // oembed display a picture of the video as well
1068 //if ($item->type != "video") {
1069 //if (($item->type != "video") and ($item->type != "photo")) {
1070 if (($type == "") OR ($type == "link")) {
1072 $type = $item->type;
1074 if (isset($item->picture))
1075 $picture = $item->picture;
1077 if (($type == "photo") AND isset($item->object_id)) {
1078 logger('fbpost_fetchwall: fetching fbid '.$item->object_id, LOGGER_DEBUG);
1079 $url = "https://graph.facebook.com/".$item->object_id."?access_token=".$access_token;
1080 $feed = fetch_url($url);
1081 $data = json_decode($feed);
1082 if (isset($data->images)) {
1083 $picture = $data->images[0]->source;
1084 logger('fbpost_fetchwall: got fbid image '.$preview, LOGGER_DEBUG);
1088 $picture = fbpost_cleanpicture($picture);
1090 if(($picture != "") && isset($item->link)) {
1091 $item->link = original_url($item->link);
1092 $content .= "\n".'[url='.$item->link.'][img]'.$picture.'[/img][/url]';
1095 $content .= "\n".'[img]'.$picture.'[/img]';
1096 // if just a link, it may be a wall photo - check
1097 if(isset($item->link))
1098 $content .= fbpost_get_photo($uid,$item->link);
1102 if(trim($_REQUEST["body"].$content.$quote) == '') {
1103 logger('facebook: empty body '.$item->id.' '.print_r($item, true));
1108 $_REQUEST["body"] .= "\n";
1111 $_REQUEST["body"] .= "[class=type-".$type."]";
1114 $_REQUEST["body"] .= trim($content);
1117 $_REQUEST["body"] .= "\n[quote]".$quote."[/quote]";
1120 $_REQUEST["body"] .= "[/class]";
1122 $_REQUEST["body"] = trim($_REQUEST["body"]);
1124 if (isset($item->place)) {
1125 if ($item->place->name or $item->place->location->street or
1126 $item->place->location->city or $item->place->location->country) {
1127 $_REQUEST["location"] = '';
1128 if ($item->place->name)
1129 $_REQUEST["location"] .= $item->place->name;
1130 if ($item->place->location->street)
1131 $_REQUEST["location"] .= " ".$item->place->location->street;
1132 if ($item->place->location->city)
1133 $_REQUEST["location"] .= " ".$item->place->location->city;
1134 if ($item->place->location->country)
1135 $_REQUEST["location"] .= " ".$item->place->location->country;
1137 $_REQUEST["location"] = trim($_REQUEST["location"]);
1139 if ($item->place->location->latitude and $item->place->location->longitude)
1140 $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
1141 .' '.substr($item->place->location->longitude, 0, 8);
1144 //print_r($_REQUEST);
1145 logger('facebook: posting for user '.$uid);
1149 set_pconfig($uid,'facebook','last_created', $lastcreated);
1152 function fbpost_get_photo($uid,$link) {
1153 $access_token = get_pconfig($uid,'facebook','access_token');
1154 if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1157 $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1159 $photo_id = $match[1];
1163 $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
1164 $j = json_decode($x);
1166 return "\n\n".'[url='.$link.'][img]'.$j->picture.'[/img][/url]';
1171 function fpost_cleanpicture($image) {
1173 if ((strpos($image, ".fbcdn.net/") OR strpos($image, "/fbcdn-photos-")) and (substr($image, -6) == "_s.jpg"))
1174 $image = substr($image, 0, -6)."_n.jpg";
1176 $queryvar = fbpost_parse_query($image);
1177 if ($queryvar['url'] != "")
1178 $image = urldecode($queryvar['url']);
1183 function fbpost_parse_query($var) {
1185 * Use this function to parse out the query array element from
1186 * the output of parse_url().
1188 $var = parse_url($var, PHP_URL_QUERY);
1189 $var = html_entity_decode($var);
1190 $var = explode('&', $var);
1193 foreach($var as $val) {
1194 $x = explode('=', $val);
1195 $arr[$x[0]] = $x[1];
1198 unset($val, $x, $var);