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