]> git.mxchange.org Git - friendica-addons.git/blob - fbpost/fbpost.php
fbsync/fbpost: Trying to be able to more often fetch pictures in its original size.
[friendica-addons.git] / fbpost / fbpost.php
1 <?php
2 /**
3  * Name: Facebook Post Connector
4  * Version: 1.3
5  * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
6  * Author: Tobias Hößl <https://github.com/CatoTH/>
7  *
8  */
9
10 /**
11  * Installing the Friendica/Facebook connector
12  *
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
15  *
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.
19  *
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.
23  */
24
25 define('FACEBOOK_DEFAULT_POLL_INTERVAL', 5); // given in minutes
26
27 require_once('include/security.php');
28
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');
38 }
39
40
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');
50 }
51
52
53 /* declare the fbpost_module function so that /fbpost url requests will land here */
54
55 function fbpost_module() {}
56
57
58
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
61
62 /**
63  * @param App $a
64  */
65 function fbpost_init(&$a) {
66
67         if($a->argc != 2)
68                 return;
69
70         $nick = $a->argv[1];
71
72         if(strlen($nick))
73                 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
74                         dbesc($nick)
75                 );
76         if(!(isset($r) && count($r)))
77                 return;
78
79         $uid           = $r[0]['uid'];
80         $auth_code     = (x($_GET, 'code') ? $_GET['code'] : '');
81         $error         = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
82
83
84         if($error)
85                 logger('fbpost_init: Error: ' . $error);
86
87         if($auth_code && $uid) {
88
89                 $appid = get_config('facebook','appid');
90                 $appsecret = get_config('facebook', 'appsecret');
91
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);
96
97                 logger('fbpost_init: returned access token: ' . $x, LOGGER_DATA);
98
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);
106                 }
107
108         }
109
110 }
111
112
113 /**
114  * @param int $uid
115  */
116 function fbpost_get_self($uid) {
117         $access_token = get_pconfig($uid,'facebook','access_token');
118         if(! $access_token)
119                 return;
120         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
121         if($s) {
122                 $j = json_decode($s);
123                 set_pconfig($uid,'facebook','self_id',(string) $j->id);
124         }
125 }
126
127
128 // This is the POST method to the facebook settings page
129 // Content is posted to Facebook in the function facebook_post_hook()
130
131 /**
132  * @param App $a
133  */
134 function fbpost_post(&$a) {
135
136         $uid = local_user();
137         if($uid){
138
139                 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
140                 set_pconfig($uid,'facebook','post_by_default', $value);
141
142                 $value = ((x($_POST,'mirror_posts')) ? intval($_POST['mirror_posts']) : 0);
143                 set_pconfig($uid,'facebook','mirror_posts', $value);
144
145                 if (!$value)
146                         del_pconfig($uid,'facebook','last_created');
147
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);
150
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]);
155
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']));
160                 }
161
162                 info( t('Settings updated.') . EOL);
163         }
164
165         return;
166 }
167
168 // Facebook settings form
169
170 /**
171  * @param App $a
172  * @return string
173  */
174 function fbpost_content(&$a) {
175
176         if(! local_user()) {
177                 notice( t('Permission denied.') . EOL);
178                 return '';
179         }
180
181
182         if(! service_class_allows(local_user(),'facebook_connect')) {
183                 notice( t('Permission denied.') . EOL);
184                 return upgrade_bool_message();
185         }
186
187
188         if($a->argc > 1 && $a->argv[1] === 'remove') {
189                 del_pconfig(local_user(),'facebook','post');
190                 info( t('Facebook Post disabled') . EOL);
191         }
192
193         require_once("mod/settings.php");
194         settings_init($a);
195
196         $o = '';
197         $accounts = array();
198
199         $fb_installed = false;
200         if (get_pconfig(local_user(),'facebook','post')) {
201                 $access_token = get_pconfig(local_user(),'facebook','access_token');
202                 if ($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);
207                         if($s) {
208                                 $accounts = json_decode($s);
209                                 if (isset($accounts->data))
210                                         $fb_installed = true;
211                         }
212
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);
218                                 if($s) {
219                                         $j = json_decode($s);
220                                         if (isset($j->data))
221                                                 $fb_installed = true;
222                                 }
223                         }
224                 }
225         }
226
227         $appid = get_config('facebook','appid');
228
229         if(! $appid) {
230                 notice( t('Facebook API key is missing.') . EOL);
231                 return '';
232         }
233
234         $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
235                 . $a->get_baseurl() . '/addon/fbpost/fbpost.css' . '" media="all" />' . "\r\n";
236
237         $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
238         $fbsync = (count($result) > 0);
239
240         if($fbsync)
241                 $title = t('Facebook Import/Export/Mirror');
242         else
243                 $title = t('Facebook Export/Mirror');
244
245         $o .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'.$title.'</h3>';
246
247         if(! $fb_installed) {
248                 $o .= '<div id="fbpost-enable-wrapper">';
249
250                 //read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access
251
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>';
254                 $o .= '</div>';
255         }
256
257         if($fb_installed) {
258                 $o .= '<div id="fbpost-disable-wrapper">';
259
260                 $o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
261
262                 $o .= '<div id="fbpost-enable-wrapper">';
263
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>';
266                 $o .= '</div>';
267
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;
273
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;
277
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;
281
282                 // List all pages
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);
289
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>";
293                 else
294                         $o .= "<option value='0-0'>".t('None')."</option>";
295
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>";
300                                 else
301                                         $o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
302                 }
303
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);
307
308                 foreach($groups->data as $group) {
309                         if ($post_to_page == $group->id)
310                                 $o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
311                         else
312                                 $o .= "<option value='".$group->id."-0'>".$group->name."</option>";
313                 }
314
315                 $o .= "</select>";
316
317                 if ($fbsync) {
318
319                         $o .= '<div class="clear"></div>';
320
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;
324
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;
328
329                 }
330                 $o .= '<p><input type="submit" name="submit" value="' . t('Save Settings') . '" /></form></div>';
331         }
332
333         return $o;
334 }
335
336 /**
337  * @param App $a
338  * @param null|object $b
339  */
340 function fbpost_plugin_settings(&$a,&$b) {
341
342         $enabled = get_pconfig(local_user(),'facebook','post');
343         $css = (($enabled) ? '' : '-disabled');
344
345         $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
346         if(count($result) > 0)
347                 $title = t('Facebook Import/Export/Mirror');
348         else
349                 $title = t('Facebook Export/Mirror');
350
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>';
353         $b .= '</div>';
354 }
355
356
357 /**
358  * @param App $a
359  * @param null|object $o
360  */
361 function fbpost_plugin_admin(&$a, &$o){
362
363
364         $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
365
366         $o .= '<h4>' . t('Facebook API Key') . '</h4>';
367
368         $appid  = get_config('facebook', 'appid'  );
369         $appsecret = get_config('facebook', 'appsecret' );
370
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>');
374
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;">';
377
378         $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
379
380 }
381
382 /**
383  * @param App $a
384  */
385
386 function fbpost_plugin_admin_post(&$a){
387         check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
388
389         if (x($_REQUEST,'fb_save_keys')) {
390                 set_config('facebook', 'appid', $_REQUEST['appid']);
391                 set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
392
393                 info(t('The new values have been saved.'));
394         }
395
396 }
397
398 /**
399  * @param App $a
400  * @param object $b
401  * @return mixed
402  */
403 function fbpost_jot_nets(&$a,&$b) {
404         if(! local_user())
405                 return;
406
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>';
413         }
414 }
415
416 /**
417  * @param App $a
418  * @param object $b
419  * @return mixed
420  */
421 function fbpost_post_hook(&$a,&$b) {
422
423         logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
424
425         if($b['deleted'] || ($b['created'] !== $b['edited']))
426                 return;
427
428         logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
429
430         // if post comes from facebook don't send it back
431         if(($b['app'] == "Facebook") AND ($b['verb'] != ACTIVITY_LIKE))
432                 return;
433
434         logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
435
436         /**
437          * Post to Facebook stream
438          */
439
440         require_once('include/group.php');
441         require_once('include/html2plain.php');
442
443
444         $reply = false;
445         $likes = false;
446
447         $deny_arr = array();
448         $allow_arr = array();
449
450         $toplevel = (($b['id'] == $b['parent']) ? true : false);
451
452
453         $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
454
455         if((!$toplevel) && ($linking)) {
456                 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
457                         intval($b['parent']),
458                         intval($b['uid'])
459                 );
460                 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
461                 //      dbesc($b['parent-uri']),
462                 //      intval($b['uid'])
463                 //);
464
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);
471                 else
472                         return;
473
474                 $u = q("SELECT * FROM user where uid = %d limit 1",
475                         intval($b['uid'])
476                 );
477                 if(! count($u))
478                         return;
479
480                 // only accept comments from the item owner. Other contacts are unknown to FB.
481
482                 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
483                         return;
484
485
486                 logger('fbpost_post_hook: facebook reply id=' . $reply);
487         }
488
489         if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
490
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']));
496
497                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
498                         $deny = array_unique(array_merge($deny_people,$deny_groups));
499
500                         $allow_str = dbesc(implode(', ',$recipients));
501                         if($allow_str) {
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'");
504                                 if(count($r))
505                                         foreach($r as $rr)
506                                                 $allow_arr[] = $rr['notify'];
507                         }
508
509                         $deny_str = dbesc(implode(', ',$deny));
510                         if($deny_str) {
511                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
512                                 if(count($r))
513                                         foreach($r as $rr)
514                                                 $deny_arr[] = $rr['notify'];
515                         }
516
517                         if(count($deny_arr) && (! count($allow_arr))) {
518
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.
524
525                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
526                                 return;
527                         }
528
529
530                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
531
532                         if((! count($allow_arr)) && (! count($deny_arr)))
533                                 return;
534                 }
535
536                 if($b['verb'] == ACTIVITY_LIKE) {
537                         $likes = true;
538                         logger('fbpost_post_hook: liking '.print_r($b, true), LOGGER_DEBUG);
539                 }
540
541
542                 $appid  = get_config('facebook', 'appid'  );
543                 $secret = get_config('facebook', 'appsecret' );
544
545                 if($appid && $secret) {
546
547                         logger('fbpost_post_hook: have appid+secret');
548
549                         $fb_token  = get_pconfig($b['uid'],'facebook','access_token');
550
551
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
555
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');
560
561                                 $msg = $b['body'];
562
563                                 logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
564
565                                 if ($toplevel) {
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"];
571
572                                         if ($msgarr["type"] != "video")
573                                                 $image = $msgarr["image"];
574
575                                         // Fallback - if message is empty
576                                         if(!strlen($msg))
577                                                 $msg = $linkname;
578
579                                         if(!strlen($msg))
580                                                 $msg = $link;
581
582                                         if(!strlen($msg))
583                                                 $msg = $image;
584                                 } else {
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));
590                                         $link = "";
591                                         $image = "";
592                                         $linkname = "";
593                                 }
594
595                                 // If there is nothing to post then exit
596                                 if(!strlen($msg))
597                                         return;
598
599                                 logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
600
601                                 $video = "";
602
603                                 if($likes) {
604                                         $postvars = array('access_token' => $fb_token);
605                                 } else {
606                                         // message, picture, link, name, caption, description, source, place, tags
607                                         //if(trim($link) != "")
608                                         //      if (@exif_imagetype($link) != 0) {
609                                         //              $image = $link;
610                                         //              $link = "";
611                                         //      }
612
613                                         $postvars = array(
614                                                 'access_token' => $fb_token,
615                                                 'message' => $msg
616                                         );
617                                         if(trim($image) != "")
618                                                 $postvars['picture'] = $image;
619
620                                         if(trim($link) != "") {
621                                                 $postvars['link'] = $link;
622
623                                                 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
624                                                         $video = $link;
625                                                 }
626                                         }
627                                         if(trim($linkname) != "")
628                                                 $postvars['name'] = $linkname;
629                                 }
630
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) . '"';
635                                         if(count($deny_arr))
636                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
637                                         $postvars['privacy'] .= '}';
638
639                                 }
640
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;
645                                 else
646                                         $target = "me";
647
648                                 if($reply) {
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
652                                         if ($video != "")
653                                                 $link = $video;
654
655                                         $postvars = array(
656                                                 'access_token' => $fb_token,
657                                                 'link' => $link,
658                                         );
659                                         if ($msg != $video)
660                                                 $postvars['message'] = $msg;
661
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
665                                         $postvars = array(
666                                                 'access_token' => $fb_token,
667                                                 'url' => $image,
668                                         );
669                                         if ($msg != $image)
670                                                 $postvars['message'] = $msg;
671
672                                         $url = 'https://graph.facebook.com/'.$target.'/photos';
673                                 //} else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
674                                 } else {
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'] . '"}';
678                                 }
679 /*                              } else {
680                                         // if its only a message and a subject and the message is larger than 500 characters then post it as note
681                                         $postvars = array(
682                                                 'access_token' => $fb_token,
683                                                 'message' => bbcode($b['body'], false, false),
684                                                 'subject' => $b['title'],
685                                         );
686                                         $url = 'https://graph.facebook.com/'.$target.'/notes';
687                                 } */
688
689                                 // Post to page?
690                                 if (!$reply and ($target != "me") and $page_access_token)
691                                         $postvars['access_token'] = $page_access_token;
692
693                                 logger('fbpost_post_hook: post to ' . $url);
694                                 logger('fbpost_post_hook: postvars: ' . print_r($postvars,true));
695
696                                 // "test_mode" prevents anything from actually being posted.
697                                 // Otherwise, let's do it.
698
699                                 if(!get_config('facebook','test_mode')) {
700                                         $x = post_url($url, $postvars);
701                                         logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
702
703                                         $retj = json_decode($x);
704                                         if($retj->id) {
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),
708                                                         intval($b['id']),
709                                                         intval($b['id'])
710                                                 );
711                                         } else {
712                                                 // Sometimes posts are accepted from facebook although it telling an error
713                                                 // This leads to endless comment flooding.
714
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']));
719                                                         if (count($r))
720                                                                 $a->contact = $r[0]["id"];
721
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);
727                                                 }
728
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);
731
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');
735
736                                                                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
737                                                                 notification(array(
738                                                                         'uid' => $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',
747                                                                 ));
748
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);
751                                                 }
752                                         }
753                                 }
754                         }
755                 }
756         }
757 }
758
759 /**
760  * @param App $app
761  * @param object $data
762  */
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]");
769         }
770 }
771
772 /**
773  * @param App $a
774  * @param object $b
775  */
776 function fbpost_post_local(&$a,&$b) {
777
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.
780
781         // This can only be triggered by a local user posting to their own wall.
782
783         if((local_user()) && (local_user() == $b['uid'])) {
784
785                 $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
786                 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
787
788                 // if API is used, default to the chosen settings
789                 // but allow a specific override
790
791                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
792                         if(! x($_REQUEST,'facebook_enable'))
793                                 $fb_enable = 1;
794                 }
795
796                 if(! $fb_enable)
797                         return;
798
799                 if(strlen($b['postopts']))
800                         $b['postopts'] .= ',';
801                 $b['postopts'] .= 'facebook';
802         }
803 }
804
805
806 /**
807  * @param App $a
808  * @param object $b
809  */
810 function fbpost_queue_hook(&$a,&$b) {
811
812         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
813                 dbesc(NETWORK_FACEBOOK)
814         );
815         if(! count($qi))
816                 return;
817
818         require_once('include/queue_fn.php');
819
820         foreach($qi as $x) {
821                 if($x['network'] !== NETWORK_FACEBOOK)
822                         continue;
823
824                 logger('fbpost_queue_hook: run');
825
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",
828                         intval($x['cid'])
829                 );
830                 if(! count($r)) {
831                         logger('fbpost_queue_hook: no user found for entry '.print_r($x, true));
832                         update_queue_time($x['id']);
833                         continue;
834                 }
835
836                 $user = $r[0];
837
838                 $appid  = get_config('facebook', 'appid'  );
839                 $secret = get_config('facebook', 'appsecret' );
840
841                 if($appid && $secret) {
842                         $fb_post   = intval(get_pconfig($user['uid'],'facebook','post'));
843                         $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
844
845                         if($fb_post && $fb_token) {
846                                 logger('fbpost_queue_hook: able to post');
847                                 require_once('library/facebook.php');
848
849                                 $z = unserialize($x['content']);
850                                 $item = $z['item'];
851                                 $j = post_url($z['url'],$z['post']);
852
853                                 $retj = json_decode($j);
854                                 if($retj->id) {
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),
858                                                 intval($item),
859                                                 intval($item)
860                                         );
861                                         logger('fbpost_queue_hook: success: ' . $j);
862                                         remove_queue_item($x['id']);
863                                 } else {
864                                         logger('fbpost_queue_hook: failed: ' . $j);
865
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']);
871                                         else
872                                                 logger('fbpost_queue_hook: Not requeued, since it seems to be received');
873                                 }
874                         } else {
875                                 logger('fbpost_queue_hook: No fb_post or fb_token.');
876                                 update_queue_time($x['id']);
877                         }
878                 } else {
879                         logger('fbpost_queue_hook: No appid or secret.');
880                         update_queue_time($x['id']);
881                 }
882         }
883 }
884
885
886 /**
887  * @return bool|string
888  */
889 function fbpost_get_app_access_token() {
890
891         $acc_token = get_config('facebook','app_access_token');
892
893         if ($acc_token !== false) return $acc_token;
894
895         $appid = get_config('facebook','appid');
896         $appsecret = get_config('facebook', 'appsecret');
897
898         if ($appid === false || $appsecret === false) {
899                 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
900                 return false;
901         }
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');
904
905         if(strpos($x,'access_token=') !== false) {
906                 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
907
908                 $token = str_replace('access_token=', '', $x);
909                 if(strpos($token,'&') !== false)
910                         $token = substr($token,0,strpos($token,'&'));
911
912                 if ($token == "") {
913                         logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
914                         return false;
915                 }
916                 set_config('facebook','app_access_token',$token);
917                 return $token;
918         } else {
919                 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
920                 return false;
921         }
922 }
923
924 function fbpost_prepare_body(&$a,&$b) {
925         if ($b["item"]["network"] != NETWORK_FACEBOOK)
926                 return;
927
928         if ($b["preview"]) {
929                 $msg = $b["item"]["body"];
930
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));
936
937                 $b['html'] = nl2br(htmlspecialchars($msg));
938         }
939 }
940
941 function fbpost_cron($a,$b) {
942         $last = get_config('facebook','last_poll');
943
944         $poll_interval = intval(get_config('facebook','poll_interval'));
945         if(! $poll_interval)
946                 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
947
948         if($last) {
949                 $next = $last + ($poll_interval * 60);
950                 if($next > time()) {
951                         logger('facebook: poll intervall not reached');
952                         return;
953                 }
954         }
955         logger('facebook: cron_start');
956
957         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
958         if(count($r)) {
959                 foreach($r as $rr) {
960                         logger('facebook: fetching for user '.$rr['uid']);
961                         fbpost_fetchwall($a, $rr['uid']);
962                 }
963         }
964
965         logger('facebook: cron_end');
966
967         set_config('facebook','last_poll', time());
968 }
969
970 function fbpost_fetchwall($a, $uid) {
971         require_once("include/oembed.php");
972         require_once('mod/item.php');
973
974         $access_token = get_pconfig($uid,'facebook','access_token');
975         $post_to_page = get_pconfig($uid,'facebook','post_to_page');
976         $lastcreated = get_pconfig($uid,'facebook','last_created');
977
978         if ((int)$post_to_page == 0)
979                 $post_to_page = "me";
980
981         $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
982
983         $first_time = ($lastcreated == "");
984
985         if ($lastcreated != "")
986                 $url .= "&since=".urlencode($lastcreated);
987
988         $feed = fetch_url($url);
989         $data = json_decode($feed);
990
991         if (!is_array($data->data))
992                 return;
993
994         $items = array_reverse($data->data);
995
996         foreach ($items as $item) {
997                 if ($item->created_time > $lastcreated)
998                         $lastcreated = $item->created_time;
999
1000                 if ($first_time)
1001                         continue;
1002
1003                 if ($item->application->id == get_config('facebook','appid'))
1004                         continue;
1005
1006                 if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
1007                         continue;
1008
1009                 if (($post_to_page != $item->from->id) AND ((int)$post_to_page != 0))
1010                         continue;
1011
1012                 if (!strstr($item->id, $item->from->id."_") AND isset($item->to) AND ((int)$post_to_page == 0))
1013                         continue;
1014
1015                 $_SESSION["authenticated"] = true;
1016                 $_SESSION["uid"] = $uid;
1017
1018                 unset($_REQUEST);
1019                 $_REQUEST["type"] = "wall";
1020                 $_REQUEST["api_source"] = true;
1021                 $_REQUEST["profile_uid"] = $uid;
1022                 $_REQUEST["source"] = "Facebook";
1023
1024                 $_REQUEST["title"] = "";
1025
1026                 $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
1027
1028                 $content = "";
1029                 $type = "";
1030
1031                 if(isset($item->name) and isset($item->link)) {
1032                         $oembed_data = oembed_fetch_url($item->link);
1033                         $type = $oembed_data->type;
1034                         $content = "[bookmark=".$item->link."]".$item->name."[/bookmark]";
1035                 } elseif (isset($item->name))
1036                         $content .= "[b]".$item->name."[/b]";
1037
1038                 $quote = "";
1039                 if(isset($item->description) and ($item->type != "photo"))
1040                         $quote = $item->description;
1041
1042                 if(isset($item->caption) and ($item->type == "photo"))
1043                         $quote = $item->caption;
1044
1045                 // Only import the picture when the message is no video
1046                 // oembed display a picture of the video as well
1047                 //if ($item->type != "video") {
1048                 //if (($item->type != "video") and ($item->type != "photo")) {
1049                 if (($type == "") OR ($type == "link")) {
1050
1051                         $type = $item->type;
1052
1053                         if (isset($item->picture))
1054                                 $picture = $item->picture;
1055
1056                         if (($type == "photo") AND isset($item->object_id)) {
1057                                  logger('fbpost_fetchwall: fetching fbid '.$item->object_id, LOGGER_DEBUG);
1058                                 $url = "https://graph.facebook.com/".$item->object_id."?access_token=".$access_token;
1059                                 $feed = fetch_url($url);
1060                                 $data = json_decode($feed);
1061                                 if (isset($data->images)) {
1062                                         $picture = $data->images[0]->source;
1063                                         logger('fbpost_fetchwall: got fbid image '.$preview, LOGGER_DEBUG);
1064                                 }
1065                         }
1066
1067                         if(($picture != "") && isset($item->link))
1068                                 $content .= "\n".'[url='.$item->link.'][img]'.$picture.'[/img][/url]';
1069                         else {
1070                                 if ($picture != "")
1071                                         $content .= "\n".'[img]'.$picture.'[/img]';
1072                                 // if just a link, it may be a wall photo - check
1073                                 if(isset($item->link))
1074                                         $content .= fbpost_get_photo($uid,$item->link);
1075                         }
1076                 }
1077
1078                 if(trim($_REQUEST["body"].$content.$quote) == '') {
1079                         logger('facebook: empty body '.$item->id.' '.print_r($item, true));
1080                         continue;
1081                 }
1082
1083                 if ($content)
1084                         $_REQUEST["body"] .= "\n";
1085
1086                 if ($type)
1087                         $_REQUEST["body"] .= "[class=type-".$type."]";
1088
1089                 if ($content)
1090                         $_REQUEST["body"] .= trim($content);
1091
1092                 if ($quote)
1093                         $_REQUEST["body"] .= "\n[quote]".$quote."[/quote]";
1094
1095                 if ($type)
1096                         $_REQUEST["body"] .= "[/class]";
1097
1098                 $_REQUEST["body"] = trim($_REQUEST["body"]);
1099
1100                 if (isset($item->place)) {
1101                         if ($item->place->name or $item->place->location->street or
1102                                 $item->place->location->city or $item->place->location->country) {
1103                                 $_REQUEST["location"] = '';
1104                                 if ($item->place->name)
1105                                         $_REQUEST["location"] .= $item->place->name;
1106                                 if ($item->place->location->street)
1107                                         $_REQUEST["location"] .= " ".$item->place->location->street;
1108                                 if ($item->place->location->city)
1109                                         $_REQUEST["location"] .= " ".$item->place->location->city;
1110                                 if ($item->place->location->country)
1111                                         $_REQUEST["location"] .= " ".$item->place->location->country;
1112
1113                                 $_REQUEST["location"] = trim($_REQUEST["location"]);
1114                         }
1115                         if ($item->place->location->latitude and $item->place->location->longitude)
1116                                 $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
1117                                                 .' '.substr($item->place->location->longitude, 0, 8);
1118                 }
1119
1120                 //print_r($_REQUEST);
1121                 logger('facebook: posting for user '.$uid);
1122                 item_post($a);
1123         }
1124
1125         set_pconfig($uid,'facebook','last_created', $lastcreated);
1126 }
1127
1128 function fbpost_get_photo($uid,$link) {
1129         $access_token = get_pconfig($uid,'facebook','access_token');
1130         if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1131                 return "";
1132
1133         $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1134         if($ret)
1135                 $photo_id = $match[1];
1136         else
1137                 return "";
1138
1139         $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
1140         $j = json_decode($x);
1141         if($j->picture)
1142                 return "\n\n".'[url='.$link.'][img]'.$j->picture.'[/img][/url]';
1143
1144         return "";
1145 }
1146
1147 function fpost_cleanpicture($image) {
1148
1149         if ((strpos($image, ".fbcdn.net/") OR strpos($image, "/fbcdn-photos-")) and (substr($image, -6) == "_s.jpg"))
1150                 $image = substr($image, 0, -6)."_n.jpg";
1151
1152         $queryvar = fbpost_parse_query($image);
1153         if ($queryvar['url'] != "")
1154                 $image = urldecode($queryvar['url']);
1155
1156         return $image;
1157 }
1158
1159 function fbpost_parse_query($var) {
1160         /**
1161          *  Use this function to parse out the query array element from
1162          *  the output of parse_url().
1163         */
1164         $var  = parse_url($var, PHP_URL_QUERY);
1165         $var  = html_entity_decode($var);
1166         $var  = explode('&', $var);
1167         $arr  = array();
1168
1169         foreach($var as $val) {
1170                 $x          = explode('=', $val);
1171                 $arr[$x[0]] = $x[1];
1172         }
1173
1174         unset($val, $x, $var);
1175         return $arr;
1176 }