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