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