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