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