]> git.mxchange.org Git - friendica-addons.git/blob - fbpost/fbpost.php
Re-enabling a once stopped mirroring now doesn't flood the timeline with old posts...
[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 }
38
39
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');
48 }
49
50
51 /* declare the fbpost_module function so that /fbpost url requests will land here */
52
53 function fbpost_module() {}
54
55
56
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
59
60 /**
61  * @param App $a
62  */
63 function fbpost_init(&$a) {
64
65         if($a->argc != 2)
66                 return;
67
68         $nick = $a->argv[1];
69
70         if(strlen($nick))
71                 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
72                                 dbesc($nick)
73                 );
74         if(!(isset($r) && count($r)))
75                 return;
76
77         $uid           = $r[0]['uid'];
78         $auth_code     = (x($_GET, 'code') ? $_GET['code'] : '');
79         $error         = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
80
81
82         if($error)
83                 logger('fbpost_init: Error: ' . $error);
84
85         if($auth_code && $uid) {
86
87                 $appid = get_config('facebook','appid');
88                 $appsecret = get_config('facebook', 'appsecret');
89
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);
94
95                 logger('fbpost_init: returned access token: ' . $x, LOGGER_DATA);
96
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);
104                 }
105
106         }
107
108 }
109
110
111 /**
112  * @param int $uid
113  */
114 function fbpost_get_self($uid) {
115         $access_token = get_pconfig($uid,'facebook','access_token');
116         if(! $access_token)
117                 return;
118         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
119         if($s) {
120                 $j = json_decode($s);
121                 set_pconfig($uid,'facebook','self_id',(string) $j->id);
122         }
123 }
124
125
126 // This is the POST method to the facebook settings page
127 // Content is posted to Facebook in the function facebook_post_hook()
128
129 /**
130  * @param App $a
131  */
132 function fbpost_post(&$a) {
133
134         $uid = local_user();
135         if($uid){
136
137                 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
138                 set_pconfig($uid,'facebook','post_by_default', $value);
139
140                 $value = ((x($_POST,'mirror_posts')) ? intval($_POST['mirror_posts']) : 0);
141                 set_pconfig($uid,'facebook','mirror_posts', $value);
142
143                 if (!$value)
144                         del_pconfig($uid,'facebook','last_created');
145
146                 $value = ((x($_POST,'suppress_view_on_friendica')) ? intval($_POST['suppress_view_on_friendica']) : 0);
147                 set_pconfig($uid,'facebook','suppress_view_on_friendica', $value);
148
149                 $value = ((x($_POST,'post_to_page')) ? $_POST['post_to_page'] : "0-0");
150                 $values = explode("-", $value);
151                 set_pconfig($uid,'facebook','post_to_page', $values[0]);
152                 set_pconfig($uid,'facebook','page_access_token', $values[1]);
153
154                 $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
155                 if (count($result) > 0) {
156                         set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
157                         set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
158                 }
159
160                 info( t('Settings updated.') . EOL);
161         }
162
163         return;
164 }
165
166 // Facebook settings form
167
168 /**
169  * @param App $a
170  * @return string
171  */
172 function fbpost_content(&$a) {
173
174         if(! local_user()) {
175                 notice( t('Permission denied.') . EOL);
176                 return '';
177         }
178
179
180         if(! service_class_allows(local_user(),'facebook_connect')) {
181                 notice( t('Permission denied.') . EOL);
182                 return upgrade_bool_message();
183         }
184
185
186         if($a->argc > 1 && $a->argv[1] === 'remove') {
187                 del_pconfig(local_user(),'facebook','post');
188                 info( t('Facebook Post disabled') . EOL);
189         }
190
191         require_once("mod/settings.php");
192         settings_init($a);
193
194         $o = '';
195         $accounts = array();
196
197         $fb_installed = false;
198         if (get_pconfig(local_user(),'facebook','post')) {
199                 $access_token = get_pconfig(local_user(),'facebook','access_token');
200                 if ($access_token) {
201                         // fetching the list of accounts to check, if facebook is working
202                         // The value is needed several lines below.
203                         $url = 'https://graph.facebook.com/me/accounts';
204                         $s = fetch_url($url."?access_token=".$access_token, false, $redirects, 10);
205                         if($s) {
206                                 $accounts = json_decode($s);
207                                 if (isset($accounts->data))
208                                         $fb_installed = true;
209                         }
210
211                         // I'm not totally sure, if this above will work in every situation,
212                         // So this old code will be called as well.
213                         if (!$fb_installed) {
214                                 $url ="https://graph.facebook.com/me/feed";
215                                 $s = fetch_url($url."?access_token=".$access_token."&limit=1", false, $redirects, 10);
216                                 if($s) {
217                                         $j = json_decode($s);
218                                         if (isset($j->data))
219                                                 $fb_installed = true;
220                                 }
221                         }
222                 }
223         }
224
225         $appid = get_config('facebook','appid');
226
227         if(! $appid) {
228                 notice( t('Facebook API key is missing.') . EOL);
229                 return '';
230         }
231
232         $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
233                 . $a->get_baseurl() . '/addon/fbpost/fbpost.css' . '" media="all" />' . "\r\n";
234
235         $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
236         $fbsync = (count($result) > 0);
237
238         if($fbsync)
239                 $title = t('Facebook Import/Export/Mirror');
240         else
241                 $title = t('Facebook Export/Mirror');
242
243         $o .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'.$title.'</h3>';
244
245         if(! $fb_installed) {
246                 $o .= '<div id="fbpost-enable-wrapper">';
247
248                 //read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access
249
250                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
251                         . $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>';
252                 $o .= '</div>';
253         }
254
255         if($fb_installed) {
256                 $o .= '<div id="fbpost-disable-wrapper">';
257
258                 $o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
259
260                 $o .= '<div id="fbpost-enable-wrapper">';
261
262                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
263                         . $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>';
264                 $o .= '</div>';
265
266                 $o .= '<div id="fbpost-post-default-form">';
267                 $o .= '<form action="fbpost" method="post" >';
268                 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
269                 $checked = (($post_by_default) ? ' checked="checked" ' : '');
270                 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
271
272                 $suppress_view_on_friendica = get_pconfig(local_user(),'facebook','suppress_view_on_friendica');
273                 $checked = (($suppress_view_on_friendica) ? ' checked="checked" ' : '');
274                 $o .= '<input type="checkbox" name="suppress_view_on_friendica" value="1"' . $checked . '/>' . ' ' . t('Suppress "View on friendica"') . EOL;
275
276                 $mirror_posts = get_pconfig(local_user(),'facebook','mirror_posts');
277                 $checked = (($mirror_posts) ? ' checked="checked" ' : '');
278                 $o .= '<input type="checkbox" name="mirror_posts" value="1"' . $checked . '/>' . ' ' . t('Mirror wall posts from facebook to friendica.') . EOL;
279
280                 // List all pages
281                 $post_to_page = get_pconfig(local_user(),'facebook','post_to_page');
282                 $page_access_token = get_pconfig(local_user(),'facebook','page_access_token');
283                 $fb_token  = get_pconfig($a->user['uid'],'facebook','access_token');
284                 //$url = 'https://graph.facebook.com/me/accounts';
285                 //$x = fetch_url($url."?access_token=".$fb_token, false, $redirects, 10);
286                 //$accounts = json_decode($x);
287
288                 $o .= t("Post to page/group:")."<select name='post_to_page'>";
289                 if (intval($post_to_page) == 0)
290                         $o .= "<option value='0-0' selected>".t('None')."</option>";
291                 else
292                         $o .= "<option value='0-0'>".t('None')."</option>";
293
294                 foreach($accounts->data as $account) {
295                         if (is_array($account->perms))
296                                 if ($post_to_page == $account->id)
297                                         $o .= "<option value='".$account->id."-".$account->access_token."' selected>".$account->name."</option>";
298                                 else
299                                         $o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
300                 }
301
302                 $url = 'https://graph.facebook.com/me/groups';
303                 $x = fetch_url($url."?access_token=".$fb_token, false, $redirects, 10);
304                 $groups = json_decode($x);
305
306                 foreach($groups->data as $group) {
307                         if ($post_to_page == $group->id)
308                                 $o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
309                         else
310                                 $o .= "<option value='".$group->id."-0'>".$group->name."</option>";
311                 }
312
313                 $o .= "</select>";
314
315                 if ($fbsync) {
316
317                         $o .= '<div class="clear"></div>';
318
319                         $sync_enabled = get_pconfig(local_user(),'fbsync','sync');
320                         $checked = (($sync_enabled) ? ' checked="checked" ' : '');
321                         $o .= '<input type="checkbox" name="fbsync" value="1"' . $checked . '/>' . ' ' . t('Import Facebook newsfeed.') . EOL;
322
323                         $create_user = get_pconfig(local_user(),'fbsync','create_user');
324                         $checked = (($create_user) ? ' checked="checked" ' : '');
325                         $o .= '<input type="checkbox" name="create_user" value="1"' . $checked . '/>' . ' ' . t('Automatically create contacts.') . EOL;
326
327                 }
328                 $o .= '<p><input type="submit" name="submit" value="' . t('Save Settings') . '" /></form></div>';
329         }
330
331         return $o;
332 }
333
334 /**
335  * @param App $a
336  * @param null|object $b
337  */
338 function fbpost_plugin_settings(&$a,&$b) {
339
340         $enabled = get_pconfig(local_user(),'facebook','post');
341         $css = (($enabled) ? '' : '-disabled');
342
343         $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
344         if(count($result) > 0)
345                 $title = t('Facebook Import/Export/Mirror');
346         else
347                 $title = t('Facebook Export/Mirror');
348
349         $b .= '<div class="settings-block">';
350         $b .= '<a href="fbpost"><img class="connector'.$css.'" src="images/facebook.png" /><h3 class="connector">'.$title.'</h3></a>';
351         $b .= '</div>';
352 }
353
354
355 /**
356  * @param App $a
357  * @param null|object $o
358  */
359 function fbpost_plugin_admin(&$a, &$o){
360
361
362         $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
363
364         $o .= '<h4>' . t('Facebook API Key') . '</h4>';
365
366         $appid  = get_config('facebook', 'appid'  );
367         $appsecret = get_config('facebook', 'appsecret' );
368
369         $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
370         $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
371         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>');
372
373         $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;">';
374         $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;">';
375
376         $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
377
378 }
379
380 /**
381  * @param App $a
382  */
383
384 function fbpost_plugin_admin_post(&$a){
385         check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
386
387         if (x($_REQUEST,'fb_save_keys')) {
388                 set_config('facebook', 'appid', $_REQUEST['appid']);
389                 set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
390
391                 info(t('The new values have been saved.'));
392         }
393
394 }
395
396 /**
397  * @param App $a
398  * @param object $b
399  * @return mixed
400  */
401 function fbpost_jot_nets(&$a,&$b) {
402         if(! local_user())
403                 return;
404
405         $fb_post = get_pconfig(local_user(),'facebook','post');
406         if(intval($fb_post) == 1) {
407                 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
408                 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
409                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> ' 
410                         . t('Post to Facebook') . '</div>';
411         }
412 }
413
414 /**
415  * @param App $a
416  * @param object $b
417  * @return mixed
418  */
419 function fbpost_post_hook(&$a,&$b) {
420
421         logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
422
423         if($b['deleted'] || ($b['created'] !== $b['edited']))
424                 return;
425
426         logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
427
428         // if post comes from facebook don't send it back
429         if(($b['app'] == "Facebook") AND ($b['verb'] != ACTIVITY_LIKE))
430                 return;
431
432         logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
433
434         /**
435          * Post to Facebook stream
436          */
437
438         require_once('include/group.php');
439         require_once('include/html2plain.php');
440
441
442         $reply = false;
443         $likes = false;
444
445         $deny_arr = array();
446         $allow_arr = array();
447
448         $toplevel = (($b['id'] == $b['parent']) ? true : false);
449
450
451         $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
452
453         if((!$toplevel) && ($linking)) {
454                 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
455                         intval($b['parent']),
456                         intval($b['uid'])
457                 );
458                 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
459                 //      dbesc($b['parent-uri']),
460                 //      intval($b['uid'])
461                 //);
462
463                 // is it a reply to a facebook post?
464                 // A reply to a toplevel post is only allowed for "real" facebook posts
465                 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
466                         $reply = substr($r[0]['uri'],4);
467                 elseif(count($r) && (substr($r[0]['extid'],0,4) === 'fb::') AND ($r[0]['id'] != $r[0]['parent']))
468                         $reply = substr($r[0]['extid'],4);
469                 else
470                         return;
471
472                 $u = q("SELECT * FROM user where uid = %d limit 1",
473                         intval($b['uid'])
474                 );
475                 if(! count($u))
476                         return;
477
478                 // only accept comments from the item owner. Other contacts are unknown to FB.
479
480                 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
481                         return;
482
483
484                 logger('fbpost_post_hook: facebook reply id=' . $reply);
485         }
486
487         if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
488
489                 if($b['private'] && $reply === false) {
490                         $allow_people = expand_acl($b['allow_cid']);
491                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
492                         $deny_people  = expand_acl($b['deny_cid']);
493                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
494
495                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
496                         $deny = array_unique(array_merge($deny_people,$deny_groups));
497
498                         $allow_str = dbesc(implode(', ',$recipients));
499                         if($allow_str) {
500                                 logger("fbpost_post_hook: private post to: ".$allow_str, LOGGER_DEBUG);
501                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
502                                 if(count($r))
503                                         foreach($r as $rr)
504                                                 $allow_arr[] = $rr['notify'];
505                         }
506
507                         $deny_str = dbesc(implode(', ',$deny));
508                         if($deny_str) {
509                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
510                                 if(count($r))
511                                         foreach($r as $rr)
512                                                 $deny_arr[] = $rr['notify'];
513                         }
514
515                         if(count($deny_arr) && (! count($allow_arr))) {
516
517                                 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
518                                 // This might cause the post to be open to public on Facebook, but only to selected members
519                                 // on another network. Since this could potentially leak a post to somebody who was denied, 
520                                 // we will skip posting it to Facebook with a slightly vague but relevant message that will 
521                                 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
522
523                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
524                                 return;
525                         }
526
527
528                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
529
530                         if((! count($allow_arr)) && (! count($deny_arr)))
531                                 return;
532                 }
533
534                 if($b['verb'] == ACTIVITY_LIKE) {
535                         $likes = true;
536                         logger('fbpost_post_hook: liking '.print_r($b, true), LOGGER_DEBUG);
537                 }
538
539
540                 $appid  = get_config('facebook', 'appid'  );
541                 $secret = get_config('facebook', 'appsecret' );
542
543                 if($appid && $secret) {
544
545                         logger('fbpost_post_hook: have appid+secret');
546
547                         $fb_token  = get_pconfig($b['uid'],'facebook','access_token');
548
549
550                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
551                         // or it's a private message with facebook participants
552                         // or it's a reply or likes action to an existing facebook post
553
554                         if($fb_token && ($toplevel || $b['private'] || $reply)) {
555                                 logger('fbpost_post_hook: able to post');
556                                 require_once('library/facebook.php');
557                                 require_once('include/bbcode.php');
558
559                                 $msg = $b['body'];
560
561                                 logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
562
563                                 if ($toplevel) {
564                                         require_once("include/plaintext.php");
565                                         $msgarr = plaintext($a, $b, 0, false);
566                                         $msg = $msgarr["text"];
567                                         $link = $msgarr["url"];
568                                         $image = $msgarr["image"];
569                                         $linkname = $msgarr["title"];
570
571                                         // Fallback - if message is empty
572                                         if(!strlen($msg))
573                                                 $msg = $linkname;
574
575                                         if(!strlen($msg))
576                                                 $msg = $link;
577
578                                         if(!strlen($msg))
579                                                 $msg = $image;
580                                 } else {
581                                         require_once("include/bbcode.php");
582                                         require_once("include/html2plain.php");
583                                         $msg = bb_CleanPictureLinks($msg);
584                                         $msg = bbcode($msg, false, false, 2, true);
585                                         $msg = trim(html2plain($msg, 0));
586                                         $link = "";
587                                         $image = "";
588                                         $linkname = "";
589                                 }
590
591                                 // If there is nothing to post then exit
592                                 if(!strlen($msg))
593                                         return;
594
595                                 logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
596
597                                 $video = "";
598
599                                 if($likes) {
600                                         $postvars = array('access_token' => $fb_token);
601                                 } else {
602                                         // message, picture, link, name, caption, description, source, place, tags
603                                         //if(trim($link) != "")
604                                         //      if (@exif_imagetype($link) != 0) {
605                                         //              $image = $link;
606                                         //              $link = "";
607                                         //      }
608
609                                         $postvars = array(
610                                                 'access_token' => $fb_token,
611                                                 'message' => $msg
612                                         );
613                                         if(trim($image) != "")
614                                                 $postvars['picture'] = $image;
615
616                                         if(trim($link) != "") {
617                                                 $postvars['link'] = $link;
618
619                                                 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
620                                                         $video = $link;
621                                                 }
622                                         }
623                                         if(trim($linkname) != "")
624                                                 $postvars['name'] = $linkname;
625                                 }
626
627                                 if(($b['private']) && ($toplevel)) {
628                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
629                                         if(count($allow_arr))
630                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
631                                         if(count($deny_arr))
632                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
633                                         $postvars['privacy'] .= '}';
634
635                                 }
636
637                                 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
638                                 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
639                                 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
640                                         $target = $post_to_page;
641                                 else
642                                         $target = "me";
643
644                                 if($reply) {
645                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
646                                 } else if (($video != "") or (($image == "") and ($link != ""))) {
647                                         // If it is a link to a video or a link without a preview picture then post it as a link
648                                         if ($video != "")
649                                                 $link = $video;
650
651                                         $postvars = array(
652                                                 'access_token' => $fb_token,
653                                                 'link' => $link,
654                                         );
655                                         if ($msg != $video)
656                                                 $postvars['message'] = $msg;
657
658                                         $url = 'https://graph.facebook.com/'.$target.'/links';
659                                 } else if (($link == "") and ($image != "")) {
660                                         // If it is only an image without a page link then post this image as a photo
661                                         $postvars = array(
662                                                 'access_token' => $fb_token,
663                                                 'url' => $image,
664                                         );
665                                         if ($msg != $image)
666                                                 $postvars['message'] = $msg;
667
668                                         $url = 'https://graph.facebook.com/'.$target.'/photos';
669                                 } else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
670                                         $url = 'https://graph.facebook.com/'.$target.'/feed';
671                                         if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
672                                                 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' .  $b['plink'] . '"}';
673                                 } else {
674                                         // if its only a message and a subject and the message is larger than 500 characters then post it as note
675                                         $postvars = array(
676                                                 'access_token' => $fb_token,
677                                                 'message' => bbcode($b['body'], false, false),
678                                                 'subject' => $b['title'],
679                                         );
680                                         $url = 'https://graph.facebook.com/'.$target.'/notes';
681                                 }
682
683                                 // Post to page?
684                                 if (!$reply and ($target != "me") and $page_access_token)
685                                         $postvars['access_token'] = $page_access_token;
686
687                                 logger('fbpost_post_hook: post to ' . $url);
688                                 logger('fbpost_post_hook: postvars: ' . print_r($postvars,true));
689
690                                 // "test_mode" prevents anything from actually being posted.
691                                 // Otherwise, let's do it.
692
693                                 if(!get_config('facebook','test_mode')) {
694                                         $x = post_url($url, $postvars);
695                                         logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
696
697                                         $retj = json_decode($x);
698                                         if($retj->id) {
699                                                 // Only set the extid when it isn't the toplevel post
700                                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
701                                                         dbesc('fb::' . $retj->id),
702                                                         intval($b['id']),
703                                                         intval($b['id'])
704                                                 );
705                                         } else {
706                                                 // Sometimes posts are accepted from facebook although it telling an error
707                                                 // This leads to endless comment flooding.
708
709                                                 // If it is a special kind of failure the post was receiced
710                                                 // Although facebook said it wasn't received ...
711                                                 if (!$likes AND (($retj->error->type != "OAuthException") OR ($retj->error->code != 2)) AND ($x <> "")) {
712                                                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
713                                                         if (count($r))
714                                                                 $a->contact = $r[0]["id"];
715
716                                                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
717                                                         require_once('include/queue_fn.php');
718                                                         add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
719                                                         logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
720                                                         notice( t('Facebook post failed. Queued for retry.') . EOL);
721                                                 }
722
723                                                 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
724                                                         logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
725
726                                                         $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
727                                                         if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
728                                                                 require_once('include/enotify.php');
729
730                                                                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
731                                                                 notification(array(
732                                                                         'uid' => $b['uid'],
733                                                                         'type' => NOTIFY_SYSTEM,
734                                                                         'system_type' => 'facebook_connection_invalid',
735                                                                         'language'     => $r[0]['language'],
736                                                                         'to_name'      => $r[0]['username'],
737                                                                         'to_email'     => $r[0]['email'],
738                                                                         'source_name'  => t('Administrator'),
739                                                                         'source_link'  => $a->config["system"]["url"],
740                                                                         'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
741                                                                 ));
742
743                                                                 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
744                                                         } else logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
745                                                 }
746                                         }
747                                 }
748                         }
749                 }
750         }
751 }
752
753 /**
754  * @param App $app
755  * @param object $data
756  */
757 function fbpost_enotify(&$app, &$data) {
758         if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
759                 $data['itemlink'] = '/fbpost';
760                 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
761                 $data['subject'] = t('Facebook connection became invalid');
762                 $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]");
763         }
764 }
765
766 /**
767  * @param App $a
768  * @param object $b
769  */
770 function fbpost_post_local(&$a,&$b) {
771
772         // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
773         // where we will discover it during background delivery.
774
775         // This can only be triggered by a local user posting to their own wall.
776
777         if((local_user()) && (local_user() == $b['uid'])) {
778
779                 $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
780                 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
781
782                 // if API is used, default to the chosen settings
783                 // but allow a specific override
784
785                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
786                         if(! x($_REQUEST,'facebook_enable'))
787                                 $fb_enable = 1;
788                 }
789
790                 if(! $fb_enable)
791                         return;
792
793                 if(strlen($b['postopts']))
794                         $b['postopts'] .= ',';
795                 $b['postopts'] .= 'facebook';
796         }
797 }
798
799
800 /**
801  * @param App $a
802  * @param object $b
803  */
804 function fbpost_queue_hook(&$a,&$b) {
805
806         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
807                 dbesc(NETWORK_FACEBOOK)
808         );
809         if(! count($qi))
810                 return;
811
812         require_once('include/queue_fn.php');
813
814         foreach($qi as $x) {
815                 if($x['network'] !== NETWORK_FACEBOOK)
816                         continue;
817
818                 logger('fbpost_queue_hook: run');
819
820                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
821                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
822                         intval($x['cid'])
823                 );
824                 if(! count($r)) {
825                         logger('fbpost_queue_hook: no user found for entry '.print_r($x, true));
826                         update_queue_time($x['id']);
827                         continue;
828                 }
829
830                 $user = $r[0];
831
832                 $appid  = get_config('facebook', 'appid'  );
833                 $secret = get_config('facebook', 'appsecret' );
834
835                 if($appid && $secret) {
836                         $fb_post   = intval(get_pconfig($user['uid'],'facebook','post'));
837                         $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
838
839                         if($fb_post && $fb_token) {
840                                 logger('fbpost_queue_hook: able to post');
841                                 require_once('library/facebook.php');
842
843                                 $z = unserialize($x['content']);
844                                 $item = $z['item'];
845                                 $j = post_url($z['url'],$z['post']);
846
847                                 $retj = json_decode($j);
848                                 if($retj->id) {
849                                         // Only set the extid when it isn't the toplevel post
850                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
851                                                 dbesc('fb::' . $retj->id),
852                                                 intval($item),
853                                                 intval($item)
854                                         );
855                                         logger('fbpost_queue_hook: success: ' . $j);
856                                         remove_queue_item($x['id']);
857                                 } else {
858                                         logger('fbpost_queue_hook: failed: ' . $j);
859
860                                         // If it is a special kind of failure the post was receiced
861                                         // Although facebook said it wasn't received ...
862                                         $ret = json_decode($j);
863                                         if (($ret->error->type != "OAuthException") OR ($ret->error->code != 2) AND ($j <> ""))
864                                                 update_queue_time($x['id']);
865                                         else
866                                                 logger('fbpost_queue_hook: Not requeued, since it seems to be received');
867                                 }
868                         } else {
869                                 logger('fbpost_queue_hook: No fb_post or fb_token.');
870                                 update_queue_time($x['id']);
871                         }
872                 } else {
873                         logger('fbpost_queue_hook: No appid or secret.');
874                         update_queue_time($x['id']);
875                 }
876         }
877 }
878
879
880 /**
881  * @return bool|string
882  */
883 function fbpost_get_app_access_token() {
884
885         $acc_token = get_config('facebook','app_access_token');
886
887         if ($acc_token !== false) return $acc_token;
888
889         $appid = get_config('facebook','appid');
890         $appsecret = get_config('facebook', 'appsecret');
891
892         if ($appid === false || $appsecret === false) {
893                 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
894                 return false;
895         }
896         logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
897         $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
898
899         if(strpos($x,'access_token=') !== false) {
900                 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
901
902                 $token = str_replace('access_token=', '', $x);
903                 if(strpos($token,'&') !== false)
904                         $token = substr($token,0,strpos($token,'&'));
905
906                 if ($token == "") {
907                         logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
908                         return false;
909                 }
910                 set_config('facebook','app_access_token',$token);
911                 return $token;
912         } else {
913                 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
914                 return false;
915         }
916 }
917
918 function fbpost_cron($a,$b) {
919         $last = get_config('facebook','last_poll');
920
921         $poll_interval = intval(get_config('facebook','poll_interval'));
922         if(! $poll_interval)
923                 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
924
925         if($last) {
926                 $next = $last + ($poll_interval * 60);
927                 if($next > time()) {
928                         logger('facebook: poll intervall not reached');
929                         return;
930                 }
931         }
932         logger('facebook: cron_start');
933
934         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
935         if(count($r)) {
936                 foreach($r as $rr) {
937                         logger('facebook: fetching for user '.$rr['uid']);
938                         fbpost_fetchwall($a, $rr['uid']);
939                 }
940         }
941
942         logger('facebook: cron_end');
943
944         set_config('facebook','last_poll', time());
945 }
946
947 function fbpost_fetchwall($a, $uid) {
948         require_once("include/oembed.php");
949
950         $access_token = get_pconfig($uid,'facebook','access_token');
951         $post_to_page = get_pconfig($uid,'facebook','post_to_page');
952         $lastcreated = get_pconfig($uid,'facebook','last_created');
953
954         if ((int)$post_to_page == 0)
955                 $post_to_page = "me";
956
957         $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
958
959         $first_time = ($lastcreated == "");
960
961         if ($lastcreated != "")
962                 $url .= "&since=".urlencode($lastcreated);
963
964         $feed = fetch_url($url);
965         $data = json_decode($feed);
966
967         if (!is_array($data->data))
968                 return;
969
970         $items = array_reverse($data->data);
971
972         foreach ($items as $item) {
973                 if ($item->created_time > $lastcreated)
974                         $lastcreated = $item->created_time;
975
976                 if ($first_time)
977                         continue;
978
979                 if ($item->application->id == get_config('facebook','appid'))
980                         continue;
981
982                 if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
983                         continue;
984
985                 if (($post_to_page != $item->from->id) AND ((int)$post_to_page != 0))
986                         continue;
987
988                 if (!strstr($item->id, $item->from->id."_") AND isset($item->to) AND ((int)$post_to_page == 0))
989                         continue;
990
991                 $_SESSION["authenticated"] = true;
992                 $_SESSION["uid"] = $uid;
993
994                 unset($_REQUEST);
995                 $_REQUEST["type"] = "wall";
996                 $_REQUEST["api_source"] = true;
997                 $_REQUEST["profile_uid"] = $uid;
998                 $_REQUEST["source"] = "Facebook";
999
1000                 $_REQUEST["title"] = "";
1001
1002                 $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
1003
1004                 $content = "";
1005                 $type = "";
1006
1007                 if(isset($item->name) and isset($item->link)) {
1008                         $oembed_data = oembed_fetch_url($item->link);
1009                         $type = $oembed_data->type;
1010                         $content = "[bookmark=".$item->link."]".$item->name."[/bookmark]";
1011                 } elseif (isset($item->name))
1012                         $content .= "[b]".$item->name."[/b]";
1013
1014                 $quote = "";
1015                 if(isset($item->description) and ($item->type != "photo"))
1016                         $quote = $item->description;
1017
1018                 if(isset($item->caption) and ($item->type == "photo"))
1019                         $quote = $item->caption;
1020
1021                 // Only import the picture when the message is no video
1022                 // oembed display a picture of the video as well
1023                 //if ($item->type != "video") {
1024                 //if (($item->type != "video") and ($item->type != "photo")) {
1025                 if (($type == "") OR ($type == "link")) {
1026
1027                         $type = $item->type;
1028
1029                         if(isset($item->picture) && isset($item->link))
1030                                 $content .= "\n".'[url='.$item->link.'][img]'.fpost_cleanpicture($item->picture).'[/img][/url]';
1031                         else {
1032                                 if (isset($item->picture))
1033                                         $content .= "\n".'[img]'.fpost_cleanpicture($item->picture).'[/img]';
1034                                 // if just a link, it may be a wall photo - check
1035                                 if(isset($item->link))
1036                                         $content .= fbpost_get_photo($uid,$item->link);
1037                         }
1038                 }
1039
1040                 if(trim($_REQUEST["body"].$content.$quote) == '') {
1041                         logger('facebook: empty body '.$item->id.' '.print_r($item, true));
1042                         continue;
1043                 }
1044
1045                 if ($content)
1046                         $_REQUEST["body"] .= "\n";
1047
1048                 if ($type)
1049                         $_REQUEST["body"] .= "[class=type-".$type."]";
1050
1051                 if ($content)
1052                         $_REQUEST["body"] .= trim($content);
1053
1054                 if ($quote)
1055                         $_REQUEST["body"] .= "\n[quote]".$quote."[/quote]";
1056
1057                 if ($type)
1058                         $_REQUEST["body"] .= "[/class]";
1059
1060                 $_REQUEST["body"] = trim($_REQUEST["body"]);
1061
1062                 if (isset($item->place)) {
1063                         if ($item->place->name or $item->place->location->street or
1064                                 $item->place->location->city or $item->place->location->country) {
1065                                 $_REQUEST["location"] = '';
1066                                 if ($item->place->name)
1067                                         $_REQUEST["location"] .= $item->place->name;
1068                                 if ($item->place->location->street)
1069                                         $_REQUEST["location"] .= " ".$item->place->location->street;
1070                                 if ($item->place->location->city)
1071                                         $_REQUEST["location"] .= " ".$item->place->location->city;
1072                                 if ($item->place->location->country)
1073                                         $_REQUEST["location"] .= " ".$item->place->location->country;
1074
1075                                 $_REQUEST["location"] = trim($_REQUEST["location"]);
1076                         }
1077                         if ($item->place->location->latitude and $item->place->location->longitude)
1078                                 $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
1079                                                 .' '.substr($item->place->location->longitude, 0, 8);
1080                 }
1081
1082                 //print_r($_REQUEST);
1083                 logger('facebook: posting for user '.$uid);
1084
1085                 require_once('mod/item.php');
1086                 item_post($a);
1087         }
1088
1089         set_pconfig($uid,'facebook','last_created', $lastcreated);
1090 }
1091
1092 function fbpost_get_photo($uid,$link) {
1093         $access_token = get_pconfig($uid,'facebook','access_token');
1094         if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1095                 return "";
1096
1097         $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1098         if($ret)
1099                 $photo_id = $match[1];
1100         else
1101                 return "";
1102
1103         $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
1104         $j = json_decode($x);
1105         if($j->picture)
1106                 return "\n\n".'[url='.$link.'][img]'.fpost_cleanpicture($j->picture).'[/img][/url]';
1107
1108         return "";
1109 }
1110
1111 function fpost_cleanpicture($image) {
1112
1113         if ((strpos($image, ".fbcdn.net/") OR strpos($image, "/fbcdn-photos-")) and (substr($image, -6) == "_s.jpg"))
1114                 $image = substr($image, 0, -6)."_n.jpg";
1115
1116         $queryvar = fbpost_parse_query($image);
1117         if ($queryvar['url'] != "")
1118                 $image = urldecode($queryvar['url']);
1119
1120         return $image;
1121 }
1122
1123 function fbpost_parse_query($var) {
1124         /**
1125          *  Use this function to parse out the query array element from
1126          *  the output of parse_url().
1127         */
1128         $var  = parse_url($var, PHP_URL_QUERY);
1129         $var  = html_entity_decode($var);
1130         $var  = explode('&', $var);
1131         $arr  = array();
1132
1133         foreach($var as $val) {
1134                 $x          = explode('=', $val);
1135                 $arr[$x[0]] = $x[1];
1136         }
1137
1138         unset($val, $x, $var);
1139         return $arr;
1140 }