]> git.mxchange.org Git - friendica-addons.git/blob - fbpost/fbpost.php
Merge pull request #255 from annando/1502-pledgie-deactivated
[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                 //export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,share_item,video_upload,status_update
252
253                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
254                         . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=publish_actions,publish_pages,user_posts,user_photos,user_status,user_videos,manage_pages">' . t('Install Facebook Post connector for this account.') . '</a>';
255                 $o .= '</div>';
256         }
257
258         if($fb_installed) {
259                 $o .= '<div id="fbpost-disable-wrapper">';
260
261                 $o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
262
263                 $o .= '<div id="fbpost-enable-wrapper">';
264
265                 //export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,share_item,video_upload,status_update
266
267                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
268                         . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=publish_actions,publish_pages,user_posts,user_photos,user_status,user_videos,manage_pages">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
269                 $o .= '</div>';
270
271                 $o .= '<div id="fbpost-post-default-form">';
272                 $o .= '<form action="fbpost" method="post" >';
273                 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
274                 $checked = (($post_by_default) ? ' checked="checked" ' : '');
275                 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
276
277                 $suppress_view_on_friendica = get_pconfig(local_user(),'facebook','suppress_view_on_friendica');
278                 $checked = (($suppress_view_on_friendica) ? ' checked="checked" ' : '');
279                 $o .= '<input type="checkbox" name="suppress_view_on_friendica" value="1"' . $checked . '/>' . ' ' . t('Suppress "View on friendica"') . EOL;
280
281                 $mirror_posts = get_pconfig(local_user(),'facebook','mirror_posts');
282                 $checked = (($mirror_posts) ? ' checked="checked" ' : '');
283                 $o .= '<input type="checkbox" name="mirror_posts" value="1"' . $checked . '/>' . ' ' . t('Mirror wall posts from facebook to friendica.') . EOL;
284
285                 // List all pages
286                 $post_to_page = get_pconfig(local_user(),'facebook','post_to_page');
287                 $page_access_token = get_pconfig(local_user(),'facebook','page_access_token');
288                 $fb_token  = get_pconfig($a->user['uid'],'facebook','access_token');
289                 //$url = 'https://graph.facebook.com/me/accounts';
290                 //$x = fetch_url($url."?access_token=".$fb_token, false, $redirects, 10);
291                 //$accounts = json_decode($x);
292
293                 $o .= t("Post to page/group:")."<select name='post_to_page'>";
294                 if (intval($post_to_page) == 0)
295                         $o .= "<option value='0-0' selected>".t('None')."</option>";
296                 else
297                         $o .= "<option value='0-0'>".t('None')."</option>";
298
299                 foreach($accounts->data as $account) {
300                         if (is_array($account->perms))
301                                 if ($post_to_page == $account->id)
302                                         $o .= "<option value='".$account->id."-".$account->access_token."' selected>".$account->name."</option>";
303                                 else
304                                         $o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
305                 }
306
307                 $url = 'https://graph.facebook.com/me/groups';
308                 $x = fetch_url($url."?access_token=".$fb_token, false, $redirects, 10);
309                 $groups = json_decode($x);
310
311                 foreach($groups->data as $group) {
312                         if ($post_to_page == $group->id)
313                                 $o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
314                         else
315                                 $o .= "<option value='".$group->id."-0'>".$group->name."</option>";
316                 }
317
318                 $o .= "</select>";
319
320                 if ($fbsync) {
321
322                         $o .= '<div class="clear"></div>';
323
324                         $sync_enabled = get_pconfig(local_user(),'fbsync','sync');
325                         $checked = (($sync_enabled) ? ' checked="checked" ' : '');
326                         $o .= '<input type="checkbox" name="fbsync" value="1"' . $checked . '/>' . ' ' . t('Import Facebook newsfeed.') . EOL;
327
328                         $create_user = get_pconfig(local_user(),'fbsync','create_user');
329                         $checked = (($create_user) ? ' checked="checked" ' : '');
330                         $o .= '<input type="checkbox" name="create_user" value="1"' . $checked . '/>' . ' ' . t('Automatically create contacts.') . EOL;
331
332                 }
333                 $o .= '<p><input type="submit" name="submit" value="' . t('Save Settings') . '" /></form></div>';
334         }
335
336         return $o;
337 }
338
339 /**
340  * @param App $a
341  * @param null|object $b
342  */
343 function fbpost_plugin_settings(&$a,&$b) {
344
345         $enabled = get_pconfig(local_user(),'facebook','post');
346         $css = (($enabled) ? '' : '-disabled');
347
348         $result = q("SELECT `installed` FROM `addon` WHERE `name` = 'fbsync' AND `installed`");
349         if(count($result) > 0)
350                 $title = t('Facebook Import/Export/Mirror');
351         else
352                 $title = t('Facebook Export/Mirror');
353
354         $b .= '<div class="settings-block">';
355         $b .= '<a href="fbpost"><img class="connector'.$css.'" src="images/facebook.png" /><h3 class="connector">'.$title.'</h3></a>';
356         $b .= '</div>';
357 }
358
359
360 /**
361  * @param App $a
362  * @param null|object $o
363  */
364 function fbpost_plugin_admin(&$a, &$o){
365
366
367         $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
368
369         $o .= '<h4>' . t('Facebook API Key') . '</h4>';
370
371         $appid  = get_config('facebook', 'appid'  );
372         $appsecret = get_config('facebook', 'appsecret' );
373
374         $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
375         $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
376         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>');
377
378         $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;">';
379         $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;">';
380
381         $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
382
383 }
384
385 /**
386  * @param App $a
387  */
388
389 function fbpost_plugin_admin_post(&$a){
390         check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
391
392         if (x($_REQUEST,'fb_save_keys')) {
393                 set_config('facebook', 'appid', $_REQUEST['appid']);
394                 set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
395
396                 info(t('The new values have been saved.'));
397         }
398
399 }
400
401 /**
402  * @param App $a
403  * @param object $b
404  * @return mixed
405  */
406 function fbpost_jot_nets(&$a,&$b) {
407         if(! local_user())
408                 return;
409
410         $fb_post = get_pconfig(local_user(),'facebook','post');
411         if(intval($fb_post) == 1) {
412                 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
413                 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
414                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> ' 
415                         . t('Post to Facebook') . '</div>';
416         }
417 }
418
419 /**
420  * @param App $a
421  * @param object $b
422  * @return mixed
423  */
424 function fbpost_post_hook(&$a,&$b) {
425
426         logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
427
428         if($b['deleted'] || ($b['created'] !== $b['edited']))
429                 return;
430
431         logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
432
433         // if post comes from facebook don't send it back
434         if($b['extid'] == NETWORK_FACEBOOK)
435                 return;
436
437         if(($b['app'] == "Facebook") AND ($b['verb'] != ACTIVITY_LIKE))
438                 return;
439
440         logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
441
442         /**
443          * Post to Facebook stream
444          */
445
446         require_once('include/group.php');
447         require_once('include/html2plain.php');
448
449
450         $reply = false;
451         $likes = false;
452
453         $deny_arr = array();
454         $allow_arr = array();
455
456         $toplevel = (($b['id'] == $b['parent']) ? true : false);
457
458
459         $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
460
461         if((!$toplevel) && ($linking)) {
462                 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
463                         intval($b['parent']),
464                         intval($b['uid'])
465                 );
466                 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
467                 //      dbesc($b['parent-uri']),
468                 //      intval($b['uid'])
469                 //);
470
471                 // is it a reply to a facebook post?
472                 // A reply to a toplevel post is only allowed for "real" facebook posts
473                 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
474                         $reply = substr($r[0]['uri'],4);
475                 elseif(count($r) && (substr($r[0]['extid'],0,4) === 'fb::') AND ($r[0]['id'] != $r[0]['parent']))
476                         $reply = substr($r[0]['extid'],4);
477                 else
478                         return;
479
480                 $u = q("SELECT * FROM user where uid = %d limit 1",
481                         intval($b['uid'])
482                 );
483                 if(! count($u))
484                         return;
485
486                 // only accept comments from the item owner. Other contacts are unknown to FB.
487
488                 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
489                         return;
490
491
492                 logger('fbpost_post_hook: facebook reply id=' . $reply);
493         }
494
495         if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
496
497                 if($b['private'] && $reply === false) {
498                         $allow_people = expand_acl($b['allow_cid']);
499                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
500                         $deny_people  = expand_acl($b['deny_cid']);
501                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
502
503                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
504                         $deny = array_unique(array_merge($deny_people,$deny_groups));
505
506                         $allow_str = dbesc(implode(', ',$recipients));
507                         if($allow_str) {
508                                 logger("fbpost_post_hook: private post to: ".$allow_str, LOGGER_DEBUG);
509                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
510                                 if(count($r))
511                                         foreach($r as $rr)
512                                                 $allow_arr[] = $rr['notify'];
513                         }
514
515                         $deny_str = dbesc(implode(', ',$deny));
516                         if($deny_str) {
517                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
518                                 if(count($r))
519                                         foreach($r as $rr)
520                                                 $deny_arr[] = $rr['notify'];
521                         }
522
523                         if(count($deny_arr) && (! count($allow_arr))) {
524
525                                 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
526                                 // This might cause the post to be open to public on Facebook, but only to selected members
527                                 // on another network. Since this could potentially leak a post to somebody who was denied, 
528                                 // we will skip posting it to Facebook with a slightly vague but relevant message that will 
529                                 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
530
531                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
532                                 return;
533                         }
534
535
536                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
537
538                         if((! count($allow_arr)) && (! count($deny_arr)))
539                                 return;
540                 }
541
542                 if($b['verb'] == ACTIVITY_LIKE) {
543                         $likes = true;
544                         logger('fbpost_post_hook: liking '.print_r($b, true), LOGGER_DEBUG);
545                 }
546
547
548                 $appid  = get_config('facebook', 'appid'  );
549                 $secret = get_config('facebook', 'appsecret' );
550
551                 if($appid && $secret) {
552
553                         logger('fbpost_post_hook: have appid+secret');
554
555                         $fb_token  = get_pconfig($b['uid'],'facebook','access_token');
556
557
558                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
559                         // or it's a private message with facebook participants
560                         // or it's a reply or likes action to an existing facebook post
561
562                         if($fb_token && ($toplevel || $b['private'] || $reply)) {
563                                 logger('fbpost_post_hook: able to post');
564                                 require_once('library/facebook.php');
565                                 require_once('include/bbcode.php');
566
567                                 $msg = $b['body'];
568
569                                 logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
570
571                                 if ($toplevel) {
572                                         require_once("include/plaintext.php");
573                                         $msgarr = plaintext($a, $b, 0, false, 9);
574                                         $msg = $msgarr["text"];
575                                         $link = $msgarr["url"];
576                                         $linkname = $msgarr["title"];
577
578                                         if ($msgarr["type"] != "video")
579                                                 $image = $msgarr["image"];
580
581                                         // Fallback - if message is empty
582                                         if(!strlen($msg))
583                                                 $msg = $linkname;
584
585                                         if(!strlen($msg))
586                                                 $msg = $link;
587
588                                         if(!strlen($msg))
589                                                 $msg = $image;
590                                 } else {
591                                         require_once("include/bbcode.php");
592                                         require_once("include/html2plain.php");
593                                         $msg = bb_CleanPictureLinks($msg);
594                                         $msg = bbcode($msg, false, false, 2, true);
595                                         $msg = trim(html2plain($msg, 0));
596                                         $link = "";
597                                         $image = "";
598                                         $linkname = "";
599                                 }
600
601                                 // If there is nothing to post then exit
602                                 if(!strlen($msg))
603                                         return;
604
605                                 logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
606
607                                 $video = "";
608
609                                 if($likes) {
610                                         $postvars = array('access_token' => $fb_token);
611                                 } else {
612                                         // message, picture, link, name, caption, description, source, place, tags
613                                         //if(trim($link) != "")
614                                         //      if (@exif_imagetype($link) != 0) {
615                                         //              $image = $link;
616                                         //              $link = "";
617                                         //      }
618
619                                         $postvars = array(
620                                                 'access_token' => $fb_token,
621                                                 'message' => $msg
622                                         );
623                                         if(trim($image) != "")
624                                                 $postvars['picture'] = $image;
625
626                                         if(trim($link) != "") {
627                                                 $postvars['link'] = $link;
628
629                                                 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
630                                                         $video = $link;
631                                                 }
632                                         }
633                                         if(trim($linkname) != "")
634                                                 $postvars['name'] = $linkname;
635                                 }
636
637                                 if(($b['private']) && ($toplevel)) {
638                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
639                                         if(count($allow_arr))
640                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
641                                         if(count($deny_arr))
642                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
643                                         $postvars['privacy'] .= '}';
644
645                                 }
646
647                                 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
648                                 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
649                                 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
650                                         $target = $post_to_page;
651                                 else
652                                         $target = "me";
653
654                                 if($reply) {
655                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
656                                 } else if (($video != "") or (($image == "") and ($link != ""))) {
657                                         // If it is a link to a video or a link without a preview picture then post it as a link
658                                         if ($video != "")
659                                                 $link = $video;
660
661                                         $postvars = array(
662                                                 'access_token' => $fb_token,
663                                                 'link' => $link,
664                                         );
665                                         if ($msg != $video)
666                                                 $postvars['message'] = $msg;
667
668                                         $url = 'https://graph.facebook.com/'.$target.'/links';
669                                 } else if (($link == "") and ($image != "")) {
670                                         // If it is only an image without a page link then post this image as a photo
671                                         $postvars = array(
672                                                 'access_token' => $fb_token,
673                                                 'url' => $image,
674                                         );
675                                         if ($msg != $image)
676                                                 $postvars['message'] = $msg;
677
678                                         $url = 'https://graph.facebook.com/'.$target.'/photos';
679                                 //} else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
680                                 } else {
681                                         $url = 'https://graph.facebook.com/'.$target.'/feed';
682                                         if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
683                                                 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' .  $b['plink'] . '"}';
684                                 }
685 /*                              } else {
686                                         // if its only a message and a subject and the message is larger than 500 characters then post it as note
687                                         $postvars = array(
688                                                 'access_token' => $fb_token,
689                                                 'message' => bbcode($b['body'], false, false),
690                                                 'subject' => $b['title'],
691                                         );
692                                         $url = 'https://graph.facebook.com/'.$target.'/notes';
693                                 } */
694
695                                 // Post to page?
696                                 if (!$reply and ($target != "me") and $page_access_token)
697                                         $postvars['access_token'] = $page_access_token;
698
699                                 logger('fbpost_post_hook: post to ' . $url);
700                                 logger('fbpost_post_hook: postvars: ' . print_r($postvars,true));
701
702                                 // "test_mode" prevents anything from actually being posted.
703                                 // Otherwise, let's do it.
704
705                                 if(!get_config('facebook','test_mode')) {
706                                         $x = post_url($url, $postvars);
707                                         logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
708
709                                         $retj = json_decode($x);
710                                         if($retj->id) {
711                                                 // Only set the extid when it isn't the toplevel post
712                                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
713                                                         dbesc('fb::' . $retj->id),
714                                                         intval($b['id']),
715                                                         intval($b['id'])
716                                                 );
717                                         } else {
718                                                 // Sometimes posts are accepted from facebook although it telling an error
719                                                 // This leads to endless comment flooding.
720
721                                                 // If it is a special kind of failure the post was receiced
722                                                 // Although facebook said it wasn't received ...
723                                                 if (!$likes AND (($retj->error->type != "OAuthException") OR ($retj->error->code != 2)) AND ($x <> "")) {
724                                                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
725                                                         if (count($r))
726                                                                 $a->contact = $r[0]["id"];
727
728                                                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
729                                                         require_once('include/queue_fn.php');
730                                                         add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
731                                                         logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
732                                                         notice( t('Facebook post failed. Queued for retry.') . EOL);
733                                                 }
734
735                                                 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
736                                                         logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
737
738                                                         $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
739                                                         if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
740                                                                 require_once('include/enotify.php');
741
742                                                                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
743                                                                 notification(array(
744                                                                         'uid' => $b['uid'],
745                                                                         'type' => NOTIFY_SYSTEM,
746                                                                         'system_type' => 'facebook_connection_invalid',
747                                                                         'language'     => $r[0]['language'],
748                                                                         'to_name'      => $r[0]['username'],
749                                                                         'to_email'     => $r[0]['email'],
750                                                                         'source_name'  => t('Administrator'),
751                                                                         'source_link'  => $a->config["system"]["url"],
752                                                                         'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
753                                                                 ));
754
755                                                                 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
756                                                         } else logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
757                                                 }
758                                         }
759                                 }
760                         }
761                 }
762         }
763 }
764
765 /**
766  * @param App $app
767  * @param object $data
768  */
769 function fbpost_enotify(&$app, &$data) {
770         if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
771                 $data['itemlink'] = '/fbpost';
772                 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
773                 $data['subject'] = t('Facebook connection became invalid');
774                 $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]");
775         }
776 }
777
778 /**
779  * @param App $a
780  * @param object $b
781  */
782 function fbpost_post_local(&$a,&$b) {
783
784         // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
785         // where we will discover it during background delivery.
786
787         // This can only be triggered by a local user posting to their own wall.
788
789         if((local_user()) && (local_user() == $b['uid'])) {
790
791                 $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
792                 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
793
794                 // if API is used, default to the chosen settings
795                 // but allow a specific override
796
797                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
798                         if(! x($_REQUEST,'facebook_enable'))
799                                 $fb_enable = 1;
800                 }
801
802                 if(! $fb_enable)
803                         return;
804
805                 if(strlen($b['postopts']))
806                         $b['postopts'] .= ',';
807                 $b['postopts'] .= 'facebook';
808         }
809 }
810
811
812 /**
813  * @param App $a
814  * @param object $b
815  */
816 function fbpost_queue_hook(&$a,&$b) {
817
818         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
819                 dbesc(NETWORK_FACEBOOK)
820         );
821         if(! count($qi))
822                 return;
823
824         require_once('include/queue_fn.php');
825
826         foreach($qi as $x) {
827                 if($x['network'] !== NETWORK_FACEBOOK)
828                         continue;
829
830                 logger('fbpost_queue_hook: run');
831
832                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
833                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
834                         intval($x['cid'])
835                 );
836                 if(! count($r)) {
837                         logger('fbpost_queue_hook: no user found for entry '.print_r($x, true));
838                         update_queue_time($x['id']);
839                         continue;
840                 }
841
842                 $user = $r[0];
843
844                 $appid  = get_config('facebook', 'appid'  );
845                 $secret = get_config('facebook', 'appsecret' );
846
847                 if($appid && $secret) {
848                         $fb_post   = intval(get_pconfig($user['uid'],'facebook','post'));
849                         $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
850
851                         if($fb_post && $fb_token) {
852                                 logger('fbpost_queue_hook: able to post');
853                                 require_once('library/facebook.php');
854
855                                 $z = unserialize($x['content']);
856                                 $item = $z['item'];
857                                 $j = post_url($z['url'],$z['post']);
858
859                                 $retj = json_decode($j);
860                                 if($retj->id) {
861                                         // Only set the extid when it isn't the toplevel post
862                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
863                                                 dbesc('fb::' . $retj->id),
864                                                 intval($item),
865                                                 intval($item)
866                                         );
867                                         logger('fbpost_queue_hook: success: ' . $j);
868                                         remove_queue_item($x['id']);
869                                 } else {
870                                         logger('fbpost_queue_hook: failed: ' . $j);
871
872                                         // If it is a special kind of failure the post was receiced
873                                         // Although facebook said it wasn't received ...
874                                         $ret = json_decode($j);
875                                         if (($ret->error->type != "OAuthException") OR ($ret->error->code != 2) AND ($j <> ""))
876                                                 update_queue_time($x['id']);
877                                         else
878                                                 logger('fbpost_queue_hook: Not requeued, since it seems to be received');
879                                 }
880                         } else {
881                                 logger('fbpost_queue_hook: No fb_post or fb_token.');
882                                 update_queue_time($x['id']);
883                         }
884                 } else {
885                         logger('fbpost_queue_hook: No appid or secret.');
886                         update_queue_time($x['id']);
887                 }
888         }
889 }
890
891
892 /**
893  * @return bool|string
894  */
895 function fbpost_get_app_access_token() {
896
897         $acc_token = get_config('facebook','app_access_token');
898
899         if ($acc_token !== false) return $acc_token;
900
901         $appid = get_config('facebook','appid');
902         $appsecret = get_config('facebook', 'appsecret');
903
904         if ($appid === false || $appsecret === false) {
905                 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
906                 return false;
907         }
908         logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
909         $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
910
911         if(strpos($x,'access_token=') !== false) {
912                 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
913
914                 $token = str_replace('access_token=', '', $x);
915                 if(strpos($token,'&') !== false)
916                         $token = substr($token,0,strpos($token,'&'));
917
918                 if ($token == "") {
919                         logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
920                         return false;
921                 }
922                 set_config('facebook','app_access_token',$token);
923                 return $token;
924         } else {
925                 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
926                 return false;
927         }
928 }
929
930 function fbpost_prepare_body(&$a,&$b) {
931         if ($b["item"]["network"] != NETWORK_FACEBOOK)
932                 return;
933
934         if ($b["preview"]) {
935                 $msg = $b["item"]["body"];
936
937                 require_once("include/bbcode.php");
938                 require_once("include/html2plain.php");
939                 $msg = bb_CleanPictureLinks($msg);
940                 $msg = bbcode($msg, false, false, 2, true);
941                 $msg = trim(html2plain($msg, 0));
942
943                 $b['html'] = nl2br(htmlspecialchars($msg));
944         }
945 }
946
947 function fbpost_cron($a,$b) {
948         $last = get_config('facebook','last_poll');
949
950         $poll_interval = intval(get_config('facebook','poll_interval'));
951         if(! $poll_interval)
952                 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
953
954         if($last) {
955                 $next = $last + ($poll_interval * 60);
956                 if($next > time()) {
957                         logger('facebook: poll intervall not reached');
958                         return;
959                 }
960         }
961         logger('facebook: cron_start');
962
963         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
964         if(count($r)) {
965                 foreach($r as $rr) {
966                         logger('facebook: fetching for user '.$rr['uid']);
967                         fbpost_fetchwall($a, $rr['uid']);
968                 }
969         }
970
971         logger('facebook: cron_end');
972
973         set_config('facebook','last_poll', time());
974 }
975
976 function fbpost_cleanpicture($url) {
977         require_once("include/Photo.php");
978
979         $urldata = parse_url($url);
980         if (isset($urldata["query"])) {
981                 parse_str($urldata["query"], $querydata);
982                 if (isset($querydata["url"]) AND (get_photo_info($querydata["url"])))
983                         return($querydata["url"]);
984         }
985         return($url);
986 }
987
988 function fbpost_fetchwall($a, $uid) {
989         require_once("include/oembed.php");
990         require_once("include/network.php");
991         require_once("include/items.php");
992         require_once("mod/item.php");
993         require_once("include/bbcode.php");
994
995         $access_token = get_pconfig($uid,'facebook','access_token');
996         $post_to_page = get_pconfig($uid,'facebook','post_to_page');
997         $mirror_page = get_pconfig($uid,'facebook','mirror_page');
998         $lastcreated = get_pconfig($uid,'facebook','last_created');
999
1000         if ((int)$post_to_page == 0)
1001                 $post_to_page = "me";
1002
1003         if ((int)$mirror_page != 0)
1004                 $post_to_page = $mirror_page;
1005
1006         $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
1007
1008         $first_time = ($lastcreated == "");
1009
1010         if ($lastcreated != "")
1011                 $url .= "&since=".urlencode($lastcreated);
1012
1013         $feed = fetch_url($url);
1014         $data = json_decode($feed);
1015
1016         if (!is_array($data->data))
1017                 return;
1018
1019         $items = array_reverse($data->data);
1020
1021         foreach ($items as $item) {
1022                 if ($item->created_time > $lastcreated)
1023                         $lastcreated = $item->created_time;
1024
1025                 if ($first_time)
1026                         continue;
1027
1028                 if ($item->application->id == get_config('facebook','appid'))
1029                         continue;
1030
1031                 //if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
1032                 if((isset($item->privacy) && ($item->privacy->value !== 'EVERYONE')) OR !isset($item->privacy))
1033                         continue;
1034
1035                 if (($post_to_page != $item->from->id) AND ((int)$post_to_page != 0))
1036                         continue;
1037
1038                 if (!strstr($item->id, $item->from->id."_") AND isset($item->to) AND ((int)$post_to_page == 0))
1039                         continue;
1040
1041                 $_SESSION["authenticated"] = true;
1042                 $_SESSION["uid"] = $uid;
1043
1044                 unset($_REQUEST);
1045                 $_REQUEST["type"] = "wall";
1046                 $_REQUEST["api_source"] = true;
1047                 $_REQUEST["profile_uid"] = $uid;
1048                 //$_REQUEST["source"] = "Facebook";
1049                 $_REQUEST["source"] = $item->application->name;
1050                 $_REQUEST["extid"] = NETWORK_FACEBOOK;
1051
1052                 $_REQUEST["title"] = "";
1053
1054                 $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
1055
1056                 $pagedata = array();
1057                 $content = "";
1058                 $pagedata["type"] = "";
1059
1060                 if(isset($item->name) and isset($item->link)) {
1061                         $item->link = original_url($item->link);
1062                         $oembed_data = oembed_fetch_url($item->link);
1063                         $pagedata["type"] = $oembed_data->type;
1064                         $pagedata["url"] = $item->link;
1065                         $pagedata["title"] = $item->name;
1066                         $content = "[bookmark=".$item->link."]".$item->name."[/bookmark]";
1067
1068                         // If a link is not only attached but also added in the body, look if it can be removed in the body.
1069                         $removedlink = trim(str_replace($item->link, "", $_REQUEST["body"]));
1070
1071                         if (($removedlink == "") OR strstr($_REQUEST["body"], $removedlink))
1072                                 $_REQUEST["body"] = $removedlink;
1073
1074                 } elseif (isset($item->name))
1075                         $content .= "[b]".$item->name."[/b]";
1076
1077                 $pagedata["text"] = "";
1078                 if(isset($item->description) and ($item->type != "photo"))
1079                         $pagedata["text"] = $item->description;
1080
1081                 if(isset($item->caption) and ($item->type == "photo"))
1082                         $pagedata["text"] = $item->caption;
1083
1084                 // Only import the picture when the message is no video
1085                 // oembed display a picture of the video as well
1086                 //if ($item->type != "video") {
1087                 //if (($item->type != "video") and ($item->type != "photo")) {
1088                 if (($pagedata["type"] == "") OR ($pagedata["type"] == "link")) {
1089
1090                         $pagedata["type"] = $item->type;
1091
1092                         if (isset($item->picture))
1093                                 $pagedata["images"][0]["src"] = $item->picture;
1094
1095                         if (($pagedata["type"] == "photo") AND isset($item->object_id)) {
1096                                  logger('fbpost_fetchwall: fetching fbid '.$item->object_id, LOGGER_DEBUG);
1097                                 $url = "https://graph.facebook.com/".$item->object_id."?access_token=".$access_token;
1098                                 $feed = fetch_url($url);
1099                                 $data = json_decode($feed);
1100                                 if (isset($data->images)) {
1101                                         $pagedata["images"][0]["src"] = $data->images[0]->source;
1102                                         logger('got fbid image from images for '.$item->object_id, LOGGER_DEBUG);
1103                                 } elseif (isset($data->source)) {
1104                                         $pagedata["images"][0]["src"] = $data->source;
1105                                         logger('got fbid image from source for '.$item->object_id, LOGGER_DEBUG);
1106                                 } elseif (isset($data->picture)) {
1107                                         $pagedata["images"][0]["src"] = $data->picture;
1108                                         logger('got fbid image from picture for '.$item->object_id, LOGGER_DEBUG);
1109                                 }
1110                         }
1111
1112                         if(trim($_REQUEST["body"].$content.$pagedata["text"]) == '') {
1113                                 logger('facebook: empty body 1 '.$item->id.' '.print_r($item, true));
1114                                 continue;
1115                         }
1116
1117                         $pagedata["images"][0]["src"] = fbpost_cleanpicture($pagedata["images"][0]["src"]);
1118
1119                         if(($pagedata["images"][0]["src"] != "") && isset($item->link)) {
1120                                 $item->link = original_url($item->link);
1121                                 $pagedata["url"] = $item->link;
1122                                 $content .= "\n".'[url='.$item->link.'][img]'.$pagedata["images"][0]["src"].'[/img][/url]';
1123                         } else {
1124                                 if ($pagedata["images"][0]["src"] != "")
1125                                         $content .= "\n".'[img]'.$pagedata["images"][0]["src"].'[/img]';
1126                                 // if just a link, it may be a wall photo - check
1127                                 if(isset($item->link))
1128                                         $content .= fbpost_get_photo($uid,$item->link);
1129                         }
1130                 }
1131
1132                 if(trim($_REQUEST["body"].$content.$pagedata["text"]) == '') {
1133                         logger('facebook: empty body 2 '.$item->id.' '.print_r($item, true));
1134                         continue;
1135                 }
1136
1137                 if ($pagedata["type"] != "")
1138                         $_REQUEST["body"] .= add_page_info_data($pagedata);
1139                 else {
1140                         if ($content)
1141                                 $_REQUEST["body"] .= "\n".trim($content);
1142
1143                         if ($pagedata["text"])
1144                                 $_REQUEST["body"] .= "\n[quote]".$pagedata["text"]."[/quote]";
1145
1146                         $_REQUEST["body"] = trim($_REQUEST["body"]);
1147                 }
1148
1149                 if (isset($item->place)) {
1150                         if ($item->place->name or $item->place->location->street or
1151                                 $item->place->location->city or $item->place->location->country) {
1152                                 $_REQUEST["location"] = '';
1153                                 if ($item->place->name)
1154                                         $_REQUEST["location"] .= $item->place->name;
1155                                 if ($item->place->location->street)
1156                                         $_REQUEST["location"] .= " ".$item->place->location->street;
1157                                 if ($item->place->location->city)
1158                                         $_REQUEST["location"] .= " ".$item->place->location->city;
1159                                 if ($item->place->location->country)
1160                                         $_REQUEST["location"] .= " ".$item->place->location->country;
1161
1162                                 $_REQUEST["location"] = trim($_REQUEST["location"]);
1163                         }
1164                         if ($item->place->location->latitude and $item->place->location->longitude)
1165                                 $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
1166                                                 .' '.substr($item->place->location->longitude, 0, 8);
1167                 }
1168
1169                 if(trim($_REQUEST["body"]) == '') {
1170                         logger('facebook: empty body 3 '.$item->id.' '.print_r($item, true));
1171                         continue;
1172                 }
1173
1174                 if(trim(strip_tags(bbcode($_REQUEST["body"], false, false))) == '') {
1175                         logger('facebook: empty body 4 '.$item->id.' '.print_r($item, true));
1176                         continue;
1177                 }
1178
1179
1180                 //print_r($_REQUEST);
1181                 logger('facebook: posting for user '.$uid);
1182                 item_post($a);
1183         }
1184
1185         set_pconfig($uid,'facebook','last_created', $lastcreated);
1186 }
1187
1188 function fbpost_get_photo($uid,$link) {
1189         $access_token = get_pconfig($uid,'facebook','access_token');
1190         if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1191                 return "";
1192
1193         $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1194         if($ret)
1195                 $photo_id = $match[1];
1196         else
1197                 return "";
1198
1199         $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
1200         $j = json_decode($x);
1201         if($j->picture)
1202                 return "\n\n".'[url='.$link.'][img]'.$j->picture.'[/img][/url]';
1203
1204         return "";
1205 }
1206
1207 function fpost_cleanpicture($image) {
1208
1209         if ((strpos($image, ".fbcdn.net/") OR strpos($image, "/fbcdn-photos-")) and (substr($image, -6) == "_s.jpg"))
1210                 $image = substr($image, 0, -6)."_n.jpg";
1211
1212         $queryvar = fbpost_parse_query($image);
1213         if ($queryvar['url'] != "")
1214                 $image = urldecode($queryvar['url']);
1215
1216         return $image;
1217 }
1218
1219 function fbpost_parse_query($var) {
1220         /**
1221          *  Use this function to parse out the query array element from
1222          *  the output of parse_url().
1223         */
1224         $var  = parse_url($var, PHP_URL_QUERY);
1225         $var  = html_entity_decode($var);
1226         $var  = explode('&', $var);
1227         $arr  = array();
1228
1229         foreach($var as $val) {
1230                 $x          = explode('=', $val);
1231                 $arr[$x[0]] = $x[1];
1232         }
1233
1234         unset($val, $x, $var);
1235         return $arr;
1236 }