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');
40 function fbpost_uninstall() {
41 unregister_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
42 unregister_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
43 unregister_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
44 unregister_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
45 unregister_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
46 unregister_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
47 unregister_hook('cron', 'addon/fbpost/fbpost.php', 'fbpost_cron');
51 /* declare the fbpost_module function so that /fbpost url requests will land here */
53 function fbpost_module() {}
57 // If a->argv[1] is a nickname, this is a callback from Facebook oauth requests.
58 // If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API
63 function fbpost_init(&$a) {
71 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
74 if(!(isset($r) && count($r)))
78 $auth_code = (x($_GET, 'code') ? $_GET['code'] : '');
79 $error = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
83 logger('fbpost_init: Error: ' . $error);
85 if($auth_code && $uid) {
87 $appid = get_config('facebook','appid');
88 $appsecret = get_config('facebook', 'appsecret');
90 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
91 . $appid . '&client_secret=' . $appsecret . '&redirect_uri='
92 . urlencode($a->get_baseurl() . '/fbpost/' . $nick)
93 . '&code=' . $auth_code);
95 logger('fbpost_init: returned access token: ' . $x, LOGGER_DATA);
97 if(strpos($x,'access_token=') !== false) {
98 $token = str_replace('access_token=', '', $x);
99 if(strpos($token,'&') !== false)
100 $token = substr($token,0,strpos($token,'&'));
101 set_pconfig($uid,'facebook','access_token',$token);
102 set_pconfig($uid,'facebook','post','1');
103 fbpost_get_self($uid);
114 function fbpost_get_self($uid) {
115 $access_token = get_pconfig($uid,'facebook','access_token');
118 $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
120 $j = json_decode($s);
121 set_pconfig($uid,'facebook','self_id',(string) $j->id);
126 // This is the POST method to the facebook settings page
127 // Content is posted to Facebook in the function facebook_post_hook()
132 function fbpost_post(&$a) {
138 $fb_limited = get_config('facebook','crestrict');
141 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
142 set_pconfig($uid,'facebook','post_by_default', $value);
144 $value = ((x($_POST,'mirror_posts')) ? intval($_POST['mirror_posts']) : 0);
145 set_pconfig($uid,'facebook','mirror_posts', $value);
147 $value = ((x($_POST,'suppress_view_on_friendica')) ? intval($_POST['suppress_view_on_friendica']) : 0);
148 set_pconfig($uid,'facebook','suppress_view_on_friendica', $value);
150 $value = ((x($_POST,'post_to_page')) ? $_POST['post_to_page'] : "0-0");
151 $values = explode("-", $value);
152 set_pconfig($uid,'facebook','post_to_page', $values[0]);
153 set_pconfig($uid,'facebook','page_access_token', $values[1]);
155 info( t('Settings updated.') . EOL);
161 // Facebook settings form
167 function fbpost_content(&$a) {
170 notice( t('Permission denied.') . EOL);
175 if(! service_class_allows(local_user(),'facebook_connect')) {
176 notice( t('Permission denied.') . EOL);
177 return upgrade_bool_message();
181 if($a->argc > 1 && $a->argv[1] === 'remove') {
182 del_pconfig(local_user(),'facebook','post');
183 info( t('Facebook Post disabled') . EOL);
188 $fb_installed = false;
189 if (get_pconfig(local_user(),'facebook','post')) {
190 $access_token = get_pconfig(local_user(),'facebook','access_token');
192 $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
194 $j = json_decode($s);
195 if (isset($j->data)) $fb_installed = true;
200 $appid = get_config('facebook','appid');
203 notice( t('Facebook API key is missing.') . EOL);
207 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
208 . $a->get_baseurl() . '/addon/fbpost/fbpost.css' . '" media="all" />' . "\r\n";
210 $o .= '<h3>' . t('Facebook Export/Mirror') . '</h3>';
212 if(! $fb_installed) {
213 $o .= '<div id="fbpost-enable-wrapper">';
215 //read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access
217 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
218 . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,create_note,share_item,video_upload,status_update">' . t('Install Facebook Post connector for this account.') . '</a>';
223 $o .= '<div id="fbpost-disable-wrapper">';
225 $o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
227 $o .= '<div id="fbpost-enable-wrapper">';
229 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
230 . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,create_note,share_item,video_upload,status_update">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
233 $o .= '<div id="fbpost-post-default-form">';
234 $o .= '<form action="fbpost" method="post" >';
235 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
236 $checked = (($post_by_default) ? ' checked="checked" ' : '');
237 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
239 $suppress_view_on_friendica = get_pconfig(local_user(),'facebook','suppress_view_on_friendica');
240 $checked = (($suppress_view_on_friendica) ? ' checked="checked" ' : '');
241 $o .= '<input type="checkbox" name="suppress_view_on_friendica" value="1"' . $checked . '/>' . ' ' . t('Suppress "View on friendica"') . EOL;
243 $mirror_posts = get_pconfig(local_user(),'facebook','mirror_posts');
244 $checked = (($mirror_posts) ? ' checked="checked" ' : '');
245 $o .= '<input type="checkbox" name="mirror_posts" value="1"' . $checked . '/>' . ' ' . t('Mirror wall posts from facebook to friendica.') . EOL;
248 $post_to_page = get_pconfig(local_user(),'facebook','post_to_page');
249 $page_access_token = get_pconfig(local_user(),'facebook','page_access_token');
250 $fb_token = get_pconfig($a->user['uid'],'facebook','access_token');
251 $url = 'https://graph.facebook.com/me/accounts';
252 $x = fetch_url($url."?access_token=".$fb_token);
253 $accounts = json_decode($x);
255 $o .= t("Post to page/group:")."<select name='post_to_page'>";
256 if (intval($post_to_page) == 0)
257 $o .= "<option value='0-0' selected>".t('None')."</option>";
259 $o .= "<option value='0-0'>".t('None')."</option>";
261 foreach($accounts->data as $account) {
262 if (is_array($account->perms))
263 if ($post_to_page == $account->id)
264 $o .= "<option value='".$account->id."-".$account->access_token."' selected>".$account->name."</option>";
266 $o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
269 $url = 'https://graph.facebook.com/me/groups';
270 $x = fetch_url($url."?access_token=".$fb_token);
271 $groups = json_decode($x);
273 foreach($groups->data as $group) {
274 if ($post_to_page == $group->id)
275 $o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
277 $o .= "<option value='".$group->id."-0'>".$group->name."</option>";
282 $o .= '<p><input type="submit" name="submit" value="' . t('Save Settings') . '" /></form></div>';
291 * @param null|object $b
293 function fbpost_plugin_settings(&$a,&$b) {
295 $b .= '<div class="settings-block">';
296 $b .= '<a href="fbpost"><h3>' . t('Facebook Export/Mirror') . '</a></h3>';
304 * @param null|object $o
306 function fbpost_plugin_admin(&$a, &$o){
309 $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
311 $o .= '<h4>' . t('Facebook API Key') . '</h4>';
313 $appid = get_config('facebook', 'appid' );
314 $appsecret = get_config('facebook', 'appsecret' );
316 $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
317 $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
318 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>');
320 $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;">';
321 $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;">';
323 $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
331 function fbpost_plugin_admin_post(&$a){
332 check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
334 if (x($_REQUEST,'fb_save_keys')) {
335 set_config('facebook', 'appid', $_REQUEST['appid']);
336 set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
338 info(t('The new values have been saved.'));
348 function fbpost_jot_nets(&$a,&$b) {
352 $fb_post = get_pconfig(local_user(),'facebook','post');
353 if(intval($fb_post) == 1) {
354 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
355 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
356 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> '
357 . t('Post to Facebook') . '</div>';
361 function fbpost_createmsg($b) {
362 require_once("include/bbcode.php");
363 require_once("include/html2plain.php");
365 $b['body'] = bb_CleanPictureLinks($b['body']);
367 // Looking for the first image
369 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
370 $image = $matches[3];
373 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
374 $image = $matches[1];
376 $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
378 // When saved into the database the content is sent through htmlspecialchars
379 // That means that we have to decode all image-urls
380 $image = htmlspecialchars_decode($image);
383 if ($b["title"] != "")
384 $body = $b["title"]."\n\n".$body;
386 if (strpos($body, "[bookmark") !== false) {
387 // splitting the text in two parts:
388 // before and after the bookmark
389 $pos = strpos($body, "[bookmark");
390 $body1 = substr($body, 0, $pos);
391 $body2 = substr($body, $pos);
393 // Removing all quotes after the bookmark
394 // they are mostly only the content after the bookmark.
395 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
396 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
398 $pos2 = strpos($body2, "[/bookmark]");
400 $body2 = substr($body2, $pos2 + 11);
402 $body = $body1.$body2;
405 // Add some newlines so that the message could be cut better
406 $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
407 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
409 // remove the recycle signs and the names since they aren't helpful on twitter
410 // $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
411 // $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
413 // At first convert the text to html
414 $html = bbcode($body, false, false, 2);
416 // Then convert it to plain text
417 //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
418 $msg = trim(html2plain($html, 0, true));
419 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
421 // Removing multiple newlines
422 while (strpos($msg, "\n\n\n") !== false)
423 $msg = str_replace("\n\n\n", "\n\n", $msg);
425 // Removing multiple spaces
426 while (strpos($msg, " ") !== false)
427 $msg = str_replace(" ", " ", $msg);
430 $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
436 // look for bookmark-bbcode and handle it with priority
437 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
439 $linkname = $matches[2];
442 $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
447 // If there is no bookmark element then take the first link
449 $links = collecturls($html);
450 if (sizeof($links) > 0) {
452 $link = current($links);
454 $multiplelinks = (sizeof($links) > 1);
459 $msglink = $b["plink"];
460 else if ($link != "")
462 else if ($multipleimages)
463 $msglink = $b["plink"];
464 else if ($image != "")
467 // Removing multiple spaces - again
468 while (strpos($msg, " ") !== false)
469 $msg = str_replace(" ", " ", $msg);
471 if ($msglink != "") {
472 // Looking if the link points to an image
473 $img_str = fetch_url($msglink);
475 $tempfile = tempnam(get_config("system","temppath"), "cache");
476 file_put_contents($tempfile, $img_str);
477 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
482 if (($image == $msglink) OR (substr($mime, 0, 6) == "image/"))
483 return(array("msg"=>trim($msg), "link"=>"", "linkname"=>$linkname, "image"=>$msglink));
485 return(array("msg"=>trim($msg), "link"=>$msglink, "linkname"=>$linkname,"image"=>$image));
493 function fbpost_post_hook(&$a,&$b) {
495 logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
497 if($b['deleted'] || ($b['created'] !== $b['edited']))
500 logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
502 // if post comes from facebook don't send it back
503 if(($b['app'] == "Facebook") AND ($b['verb'] != ACTIVITY_LIKE))
506 logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
509 * Post to Facebook stream
512 require_once('include/group.php');
513 require_once('include/html2plain.php');
520 $allow_arr = array();
522 $toplevel = (($b['id'] == $b['parent']) ? true : false);
525 $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
527 if((!$toplevel) && ($linking)) {
528 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
529 intval($b['parent']),
532 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
533 // dbesc($b['parent-uri']),
537 // is it a reply to a facebook post?
538 // A reply to a toplevel post is only allowed for "real" facebook posts
539 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
540 $reply = substr($r[0]['uri'],4);
541 elseif(count($r) && (substr($r[0]['extid'],0,4) === 'fb::') AND ($r[0]['id'] != $r[0]['parent']))
542 $reply = substr($r[0]['extid'],4);
546 $u = q("SELECT * FROM user where uid = %d limit 1",
552 // only accept comments from the item owner. Other contacts are unknown to FB.
554 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
558 logger('fbpost_post_hook: facebook reply id=' . $reply);
561 if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
563 if($b['private'] && $reply === false) {
564 $allow_people = expand_acl($b['allow_cid']);
565 $allow_groups = expand_groups(expand_acl($b['allow_gid']));
566 $deny_people = expand_acl($b['deny_cid']);
567 $deny_groups = expand_groups(expand_acl($b['deny_gid']));
569 $recipients = array_unique(array_merge($allow_people,$allow_groups));
570 $deny = array_unique(array_merge($deny_people,$deny_groups));
572 $allow_str = dbesc(implode(', ',$recipients));
574 logger("fbpost_post_hook: private post to: ".$allow_str, LOGGER_DEBUG);
575 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
578 $allow_arr[] = $rr['notify'];
581 $deny_str = dbesc(implode(', ',$deny));
583 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
586 $deny_arr[] = $rr['notify'];
589 if(count($deny_arr) && (! count($allow_arr))) {
591 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
592 // This might cause the post to be open to public on Facebook, but only to selected members
593 // on another network. Since this could potentially leak a post to somebody who was denied,
594 // we will skip posting it to Facebook with a slightly vague but relevant message that will
595 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
597 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
602 // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
604 if((! count($allow_arr)) && (! count($deny_arr)))
608 if($b['verb'] == ACTIVITY_LIKE) {
610 logger('fbpost_post_hook: liking '.print_r($b, true), LOGGER_DEBUG);
614 $appid = get_config('facebook', 'appid' );
615 $secret = get_config('facebook', 'appsecret' );
617 if($appid && $secret) {
619 logger('fbpost_post_hook: have appid+secret');
621 $fb_token = get_pconfig($b['uid'],'facebook','access_token');
624 // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
625 // or it's a private message with facebook participants
626 // or it's a reply or likes action to an existing facebook post
628 if($fb_token && ($toplevel || $b['private'] || $reply)) {
629 logger('fbpost_post_hook: able to post');
630 require_once('library/facebook.php');
631 require_once('include/bbcode.php');
635 logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
638 $msgarr = fbpost_createmsg($b);
639 $msg = $msgarr["msg"];
640 $link = $msgarr["link"];
641 $image = $msgarr["image"];
642 $linkname = $msgarr["linkname"];
644 // Fallback - if message is empty
654 require_once("include/bbcode.php");
655 require_once("include/html2plain.php");
656 $msg = bb_CleanPictureLinks($msg);
657 $msg = bbcode($msg, false, false, 2, true);
658 $msg = trim(html2plain($msg, 0));
664 // If there is nothing to post then exit
668 logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
673 $postvars = array('access_token' => $fb_token);
675 // message, picture, link, name, caption, description, source, place, tags
676 //if(trim($link) != "")
677 // if (@exif_imagetype($link) != 0) {
683 'access_token' => $fb_token,
686 if(trim($image) != "")
687 $postvars['picture'] = $image;
689 if(trim($link) != "") {
690 $postvars['link'] = $link;
692 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
696 if(trim($linkname) != "")
697 $postvars['name'] = $linkname;
700 if(($b['private']) && ($toplevel)) {
701 $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
702 if(count($allow_arr))
703 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
705 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
706 $postvars['privacy'] .= '}';
710 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
711 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
712 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
713 $target = $post_to_page;
718 $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
719 } else if (($video != "") or (($image == "") and ($link != ""))) {
720 // If it is a link to a video or a link without a preview picture then post it as a link
725 'access_token' => $fb_token,
729 $postvars['message'] = $msg;
731 $url = 'https://graph.facebook.com/'.$target.'/links';
732 } else if (($link == "") and ($image != "")) {
733 // If it is only an image without a page link then post this image as a photo
735 'access_token' => $fb_token,
739 $postvars['message'] = $msg;
741 $url = 'https://graph.facebook.com/'.$target.'/photos';
742 } else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
743 $url = 'https://graph.facebook.com/'.$target.'/feed';
744 if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
745 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
747 // if its only a message and a subject and the message is larger than 500 characters then post it as note
749 'access_token' => $fb_token,
750 'message' => bbcode($b['body'], false, false),
751 'subject' => $b['title'],
753 $url = 'https://graph.facebook.com/'.$target.'/notes';
757 if (!$reply and ($target != "me") and $page_access_token)
758 $postvars['access_token'] = $page_access_token;
760 logger('fbpost_post_hook: post to ' . $url);
761 logger('fbpost_post_hook: postvars: ' . print_r($postvars,true));
763 // "test_mode" prevents anything from actually being posted.
764 // Otherwise, let's do it.
766 if(!get_config('facebook','test_mode')) {
767 $x = post_url($url, $postvars);
768 logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
770 $retj = json_decode($x);
772 // Only set the extid when it isn't the toplevel post
773 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
774 dbesc('fb::' . $retj->id),
779 // Sometimes posts are accepted from facebook although it telling an error
780 // This leads to endless comment flooding.
782 // If it is a special kind of failure the post was receiced
783 // Although facebook said it wasn't received ...
784 if (!$likes AND (($retj->error->type != "OAuthException") OR ($retj->error->code != 2)) AND ($x <> "")) {
785 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
787 $a->contact = $r[0]["id"];
789 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
790 require_once('include/queue_fn.php');
791 add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
792 logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
793 notice( t('Facebook post failed. Queued for retry.') . EOL);
796 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
797 logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
799 $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
800 if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
801 require_once('include/enotify.php');
803 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
806 'type' => NOTIFY_SYSTEM,
807 'system_type' => 'facebook_connection_invalid',
808 'language' => $r[0]['language'],
809 'to_name' => $r[0]['username'],
810 'to_email' => $r[0]['email'],
811 'source_name' => t('Administrator'),
812 'source_link' => $a->config["system"]["url"],
813 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
816 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
817 } else logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
828 * @param object $data
830 function fbpost_enotify(&$app, &$data) {
831 if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
832 $data['itemlink'] = '/fbpost';
833 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
834 $data['subject'] = t('Facebook connection became invalid');
835 $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]");
843 function fbpost_post_local(&$a,&$b) {
845 // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
846 // where we will discover it during background delivery.
848 // This can only be triggered by a local user posting to their own wall.
850 if((local_user()) && (local_user() == $b['uid'])) {
852 $fb_post = intval(get_pconfig(local_user(),'facebook','post'));
853 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
855 // if API is used, default to the chosen settings
856 // but allow a specific override
858 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
859 if(! x($_REQUEST,'facebook_enable'))
866 if(strlen($b['postopts']))
867 $b['postopts'] .= ',';
868 $b['postopts'] .= 'facebook';
877 function fbpost_queue_hook(&$a,&$b) {
879 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
880 dbesc(NETWORK_FACEBOOK)
885 require_once('include/queue_fn.php');
888 if($x['network'] !== NETWORK_FACEBOOK)
891 logger('fbpost_queue_hook: run');
893 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
894 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
898 logger('fbpost_queue_hook: no user found for entry '.print_r($x, true));
899 update_queue_time($x['id']);
905 $appid = get_config('facebook', 'appid' );
906 $secret = get_config('facebook', 'appsecret' );
908 if($appid && $secret) {
909 $fb_post = intval(get_pconfig($user['uid'],'facebook','post'));
910 $fb_token = get_pconfig($user['uid'],'facebook','access_token');
912 if($fb_post && $fb_token) {
913 logger('fbpost_queue_hook: able to post');
914 require_once('library/facebook.php');
916 $z = unserialize($x['content']);
918 $j = post_url($z['url'],$z['post']);
920 $retj = json_decode($j);
922 // Only set the extid when it isn't the toplevel post
923 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
924 dbesc('fb::' . $retj->id),
928 logger('fbpost_queue_hook: success: ' . $j);
929 remove_queue_item($x['id']);
931 logger('fbpost_queue_hook: failed: ' . $j);
933 // If it is a special kind of failure the post was receiced
934 // Although facebook said it wasn't received ...
935 $ret = json_decode($j);
936 if (($ret->error->type != "OAuthException") OR ($ret->error->code != 2) AND ($j <> ""))
937 update_queue_time($x['id']);
939 logger('fbpost_queue_hook: Not requeued, since it seems to be received');
942 logger('fbpost_queue_hook: No fb_post or fb_token.');
943 update_queue_time($x['id']);
946 logger('fbpost_queue_hook: No appid or secret.');
947 update_queue_time($x['id']);
954 * @return bool|string
956 function fbpost_get_app_access_token() {
958 $acc_token = get_config('facebook','app_access_token');
960 if ($acc_token !== false) return $acc_token;
962 $appid = get_config('facebook','appid');
963 $appsecret = get_config('facebook', 'appsecret');
965 if ($appid === false || $appsecret === false) {
966 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
969 logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
970 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
972 if(strpos($x,'access_token=') !== false) {
973 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
975 $token = str_replace('access_token=', '', $x);
976 if(strpos($token,'&') !== false)
977 $token = substr($token,0,strpos($token,'&'));
980 logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
983 set_config('facebook','app_access_token',$token);
986 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
991 function fbpost_cron($a,$b) {
992 $last = get_config('facebook','last_poll');
994 $poll_interval = intval(get_config('facebook','poll_interval'));
996 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
999 $next = $last + ($poll_interval * 60);
1000 if($next > time()) {
1001 logger('facebook: poll intervall not reached');
1005 logger('facebook: cron_start');
1007 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
1009 foreach($r as $rr) {
1010 logger('facebook: fetching for user '.$rr['uid']);
1011 fbpost_fetchwall($a, $rr['uid']);
1015 logger('facebook: cron_end');
1017 set_config('facebook','last_poll', time());
1020 function fbpost_fetchwall($a, $uid) {
1021 require_once("include/oembed.php");
1023 $access_token = get_pconfig($uid,'facebook','access_token');
1024 $post_to_page = get_pconfig($uid,'facebook','post_to_page');
1025 $lastcreated = get_pconfig($uid,'facebook','last_created');
1027 if ((int)$post_to_page == 0)
1028 $post_to_page = "me";
1030 $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
1032 $first_time = ($lastcreated == "");
1034 if ($lastcreated != "")
1035 $url .= "&since=".urlencode($lastcreated);
1037 $feed = fetch_url($url);
1038 $data = json_decode($feed);
1040 if (!is_array($data->data))
1043 $items = array_reverse($data->data);
1045 foreach ($items as $item) {
1046 if ($item->created_time > $lastcreated)
1047 $lastcreated = $item->created_time;
1052 if ($item->application->id == get_config('facebook','appid'))
1055 if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
1058 if (($post_to_page != $item->from->id) AND ((int)$post_to_page != 0))
1061 if (!strstr($item->id, $item->from->id."_") AND isset($item->to) AND ((int)$post_to_page == 0))
1064 $_SESSION["authenticated"] = true;
1065 $_SESSION["uid"] = $uid;
1068 $_REQUEST["type"] = "wall";
1069 $_REQUEST["api_source"] = true;
1070 $_REQUEST["profile_uid"] = $uid;
1071 $_REQUEST["source"] = "Facebook";
1073 $_REQUEST["title"] = "";
1075 $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
1080 if(isset($item->name) and isset($item->link)) {
1081 $oembed_data = oembed_fetch_url($item->link);
1082 $type = $oembed_data->type;
1083 $content = "[bookmark=".$item->link."]".$item->name."[/bookmark]";
1084 } elseif (isset($item->name))
1085 $content .= "[b]".$item->name."[/b]";
1088 if(isset($item->description) and ($item->type != "photo"))
1089 $quote = $item->description;
1091 if(isset($item->caption) and ($item->type == "photo"))
1092 $quote = $item->caption;
1094 // Only import the picture when the message is no video
1095 // oembed display a picture of the video as well
1096 //if ($item->type != "video") {
1097 //if (($item->type != "video") and ($item->type != "photo")) {
1098 if (($type == "") OR ($type == "link")) {
1100 $type = $item->type;
1102 if(isset($item->picture) && isset($item->link))
1103 $content .= "\n".'[url='.$item->link.'][img]'.fpost_cleanpicture($item->picture).'[/img][/url]';
1105 if (isset($item->picture))
1106 $content .= "\n".'[img]'.fpost_cleanpicture($item->picture).'[/img]';
1107 // if just a link, it may be a wall photo - check
1108 if(isset($item->link))
1109 $content .= fbpost_get_photo($uid,$item->link);
1113 if(trim($_REQUEST["body"].$content.$quote) == '') {
1114 logger('facebook: empty body '.$item->id.' '.print_r($item, true));
1119 $_REQUEST["body"] .= "\n";
1122 $_REQUEST["body"] .= "[class=type-".$type."]";
1125 $_REQUEST["body"] .= trim($content);
1128 $_REQUEST["body"] .= "\n[quote]".$quote."[/quote]";
1131 $_REQUEST["body"] .= "[/class]";
1133 $_REQUEST["body"] = trim($_REQUEST["body"]);
1135 if (isset($item->place)) {
1136 if ($item->place->name or $item->place->location->street or
1137 $item->place->location->city or $item->place->location->country) {
1138 $_REQUEST["location"] = '';
1139 if ($item->place->name)
1140 $_REQUEST["location"] .= $item->place->name;
1141 if ($item->place->location->street)
1142 $_REQUEST["location"] .= " ".$item->place->location->street;
1143 if ($item->place->location->city)
1144 $_REQUEST["location"] .= " ".$item->place->location->city;
1145 if ($item->place->location->country)
1146 $_REQUEST["location"] .= " ".$item->place->location->country;
1148 $_REQUEST["location"] = trim($_REQUEST["location"]);
1150 if ($item->place->location->latitude and $item->place->location->longitude)
1151 $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
1152 .' '.substr($item->place->location->longitude, 0, 8);
1155 //print_r($_REQUEST);
1156 logger('facebook: posting for user '.$uid);
1158 require_once('mod/item.php');
1162 set_pconfig($uid,'facebook','last_created', $lastcreated);
1165 function fbpost_get_photo($uid,$link) {
1166 $access_token = get_pconfig($uid,'facebook','access_token');
1167 if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1170 $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1172 $photo_id = $match[1];
1176 $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
1177 $j = json_decode($x);
1179 return "\n\n".'[url='.$link.'][img]'.fpost_cleanpicture($j->picture).'[/img][/url]';
1184 function fpost_cleanpicture($image) {
1186 if ((strpos($image, ".fbcdn.net/") OR strpos($image, "/fbcdn-photos-")) and (substr($image, -6) == "_s.jpg"))
1187 $image = substr($image, 0, -6)."_n.jpg";
1189 $queryvar = fbpost_parse_query($image);
1190 if ($queryvar['url'] != "")
1191 $image = urldecode($queryvar['url']);
1196 function fbpost_parse_query($var) {
1198 * Use this function to parse out the query array element from
1199 * the output of parse_url().
1201 $var = parse_url($var, PHP_URL_QUERY);
1202 $var = html_entity_decode($var);
1203 $var = explode('&', $var);
1206 foreach($var as $val) {
1207 $x = explode('=', $val);
1208 $arr[$x[0]] = $x[1];
1211 unset($val, $x, $var);