]> git.mxchange.org Git - friendica-addons.git/blob - fbpost/fbpost.php
fbpost: Beautifying the import to friendica
[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_ShareAttributes($match) {
361
362         $attributes = $match[1];
363
364         $author = "";
365         preg_match("/author='(.*?)'/ism", $attributes, $matches);
366         if ($matches[1] != "")
367                 $author = $matches[1];
368
369         preg_match('/author="(.*?)"/ism', $attributes, $matches);
370         if ($matches[1] != "")
371                 $author = $matches[1];
372
373         $headline = '<div class="shared_header">';
374
375         $headline .= sprintf(t('%s:'), $author);
376
377         $headline .= "</div>";
378
379         //$text = "<br />".$headline."</strong><blockquote>".$match[2]."</blockquote>";
380         $text = "\n\t".$match[2].":\t";
381
382         return($text);
383 }
384
385
386 /**
387  * @param App $a
388  * @param object $b
389  * @return mixed
390  */
391 function fbpost_post_hook(&$a,&$b) {
392
393
394         if($b['deleted'] || ($b['created'] !== $b['edited']))
395                 return;
396
397         // if post comes from facebook don't send it back
398         if($b['app'] == "Facebook")
399                 return;
400
401         /**
402          * Post to Facebook stream
403          */
404
405         require_once('include/group.php');
406         require_once('include/html2plain.php');
407
408         logger('Facebook post');
409
410         $reply = false;
411         $likes = false;
412
413         $deny_arr = array();
414         $allow_arr = array();
415
416         $toplevel = (($b['id'] == $b['parent']) ? true : false);
417
418
419         $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
420
421         if((! $toplevel) && ($linking)) {
422                 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
423                         intval($b['parent']),
424                         intval($b['uid'])
425                 );
426                 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
427                         $reply = substr($r[0]['uri'],4);
428                 elseif(count($r) && substr($r[0]['extid'],0,4) === 'fb::')
429                         $reply = substr($r[0]['extid'],4);
430                 else
431                         return;
432
433                 $u = q("SELECT * FROM user where uid = %d limit 1",
434                         intval($b['uid'])
435                 );
436                 if(! count($u))
437                         return;
438
439                 // only accept comments from the item owner. Other contacts are unknown to FB.
440
441                 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
442                         return;
443
444
445                 logger('facebook reply id=' . $reply);
446         }
447
448         if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
449
450                 if($b['private'] && $reply === false) {
451                         $allow_people = expand_acl($b['allow_cid']);
452                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
453                         $deny_people  = expand_acl($b['deny_cid']);
454                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
455
456                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
457                         $deny = array_unique(array_merge($deny_people,$deny_groups));
458
459                         $allow_str = dbesc(implode(', ',$recipients));
460                         if($allow_str) {
461                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'"); 
462                                 if(count($r))
463                                         foreach($r as $rr)
464                                                 $allow_arr[] = $rr['notify'];
465                         }
466
467                         $deny_str = dbesc(implode(', ',$deny));
468                         if($deny_str) {
469                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'"); 
470                                 if(count($r))
471                                         foreach($r as $rr)
472                                                 $deny_arr[] = $rr['notify'];
473                         }
474
475                         if(count($deny_arr) && (! count($allow_arr))) {
476
477                                 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
478                                 // This might cause the post to be open to public on Facebook, but only to selected members
479                                 // on another network. Since this could potentially leak a post to somebody who was denied, 
480                                 // we will skip posting it to Facebook with a slightly vague but relevant message that will 
481                                 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
482
483                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
484                                 return;
485                         }
486
487
488                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
489
490                         if((! count($allow_arr)) && (! count($deny_arr)))
491                                 return;
492                 }
493
494                 if($b['verb'] == ACTIVITY_LIKE)
495                         $likes = true;
496
497
498                 $appid  = get_config('facebook', 'appid'  );
499                 $secret = get_config('facebook', 'appsecret' );
500
501                 if($appid && $secret) {
502
503                         logger('facebook: have appid+secret');
504
505                         $fb_token  = get_pconfig($b['uid'],'facebook','access_token');
506
507
508                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
509                         // or it's a private message with facebook participants
510                         // or it's a reply or likes action to an existing facebook post
511
512                         if($fb_token && ($toplevel || $b['private'] || $reply)) {
513                                 logger('facebook: able to post');
514                                 require_once('library/facebook.php');
515                                 require_once('include/bbcode.php');
516
517                                 $msg = $b['body'];
518
519                                 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
520
521                                 // make links readable before we strip the code
522
523                                 // unless it's a dislike - just send the text as a comment
524
525                                 // if($b['verb'] == ACTIVITY_DISLIKE)
526                                 //      $msg = trim(strip_tags(bbcode($msg)));
527
528                                 // Old code
529                                 /*$search_str = $a->get_baseurl() . '/search';
530
531                                 if(preg_match("/\[url=(.*?)\](.*?)\[\/url\]/is",$msg,$matches)) {
532
533                                         // don't use hashtags for message link
534
535                                         if(strpos($matches[2],$search_str) === false) {
536                                                 $link = $matches[1];
537                                                 if(substr($matches[2],0,5) != '[img]')
538                                                         $linkname = $matches[2];
539                                         }
540                                 }
541
542                                 // strip tag links to avoid link clutter, this really should be 
543                                 // configurable because we're losing information
544
545                                 $msg = preg_replace("/\#\[url=(.*?)\](.*?)\[\/url\]/is",'#$2',$msg);
546
547                                 // provide the link separately for normal links
548                                 $msg = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is",'$2 $1',$msg);
549
550                                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$msg,$matches))
551                                         $image = $matches[1];
552
553                                 $msg = preg_replace("/\[img\](.*?)\[\/img\]/is", t('Image: ') . '$1', $msg);
554
555                                 if((strpos($link,z_root()) !== false) && (! $image))
556                                         $image = $a->get_baseurl() . '/images/friendica-64.jpg';
557
558                                 $msg = trim(strip_tags(bbcode($msg)));*/
559
560                                 // New code
561
562                                 // Looking for the first image
563                                 $image = '';
564                                 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
565                                         $image = $matches[3];
566
567                                 if ($image == '')
568                                         if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
569                                                 $image = $matches[1];
570
571                                 // When saved into the database the content is sent through htmlspecialchars
572                                 // That means that we have to decode all image-urls
573                                 $image = htmlspecialchars_decode($image);
574
575                                 // Checking for a bookmark element
576                                 $body = $b['body'];
577                                 if (strpos($body, "[bookmark") !== false) {
578                                         // splitting the text in two parts:
579                                         // before and after the bookmark
580                                         $pos = strpos($body, "[bookmark");
581                                         $body1 = substr($body, 0, $pos);
582                                         $body2 = substr($body, $pos);
583
584                                         // Removing the bookmark and all quotes after the bookmark
585                                         // they are mostly only the content after the bookmark.
586                                         $body2 = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'',$body2);
587                                         $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
588                                         $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
589
590                                         $body = $body1.$body2;
591                                 }
592
593                                 // Convert recycle signs
594                                 $body = str_replace("\t", " ", $body);
595                                 // recycle 1
596                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
597                                 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
598                                 // recycle 2 (Test)
599                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
600                                 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
601
602                                 // share element
603                                 $body = preg_replace_callback("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]/ism","fbpost_ShareAttributes", $body);
604
605                                 $bodyparts = explode("\t", $body);
606                                 // Doesn't help with multiple repeats - the problem has to be solved later
607                                 if (sizeof($bodyparts) == 3) {
608                                         $html = bbcode($bodyparts[2], false, false);
609                                         $test = trim(html2plain($html, 0, true));
610
611                                         if (trim($bodyparts[0]) == "")
612                                                 $body = trim($bodyparts[2]);
613                                         else if (trim($test) == "")
614                                                 $body = trim($bodyparts[0]);
615                                         else
616                                                 $body = trim($bodyparts[0])."\n\n".trim($bodyparts[1])."[quote]".trim($bodyparts[2])."[/quote]";
617                                 } else
618                                         $body = str_replace("\t", "", $body);
619
620                                 // At first convert the text to html
621                                 $html = bbcode($body, false, false);
622
623                                 // Then convert it to plain text
624                                 $msg = trim($b['title']." \n\n".html2plain($html, 0, true));
625
626                                 // Removing useless spaces
627                                 if (substr($msg, -2) == "«")
628                                         $msg = trim(substr($msg, 0, -2))."«";
629
630                                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
631
632                                 // Removing multiple newlines
633                                 while (strpos($msg, "\n\n\n") !== false)
634                                         $msg = str_replace("\n\n\n", "\n\n", $msg);
635
636                                 // add any attachments as text urls
637                                 $arr = explode(',',$b['attach']);
638
639                                 if(count($arr)) {
640                                         $msg .= "\n";
641                                         foreach($arr as $r) {
642                                                 $matches = false;
643                                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
644                                                 if($cnt) {
645                                                         $msg .= "\n".$matches[1];
646                                                 }
647                                         }
648                                 }
649
650                                 $link = '';
651                                 $linkname = '';
652                                 // look for bookmark-bbcode and handle it with priority
653                                 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
654                                         $link = $matches[1];
655                                         $linkname = $matches[2];
656                                 }
657
658                                 // If there is no bookmark element then take the first link
659                                 if ($link == '') {
660                                         $links = collecturls($html);
661                                         if (sizeof($links) > 0) {
662                                                 reset($links);
663                                                 $link = current($links);
664                                         }
665                                 }
666
667                                 // Remove trailing and leading spaces
668                                 $msg = trim($msg);
669
670
671                                 // Fallback - if message is empty
672                                 if(!strlen($msg))
673                                         $msg = $linkname;
674
675                                 if(!strlen($msg))
676                                         $msg = $link;
677
678                                 if(!strlen($msg))
679                                         $msg = $image;
680
681                                 // If there is nothing to post then exit
682                                 if(!strlen($msg))
683                                         return;
684
685                                 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
686
687                                 $video = "";
688
689                                 if($likes) {
690                                         $postvars = array('access_token' => $fb_token);
691                                 } else {
692                                         // message, picture, link, name, caption, description, source, place, tags
693                                         if(trim($link) != "")
694                                                 if (@exif_imagetype($link) != 0) {
695                                                         $image = $link;
696                                                         $link = "";
697                                                 }
698
699                                         $postvars = array(
700                                                 'access_token' => $fb_token,
701                                                 'message' => $msg
702                                         );
703                                         if(trim($image) != "")
704                                                 $postvars['picture'] = $image;
705
706                                         if(trim($link) != "") {
707                                                 $postvars['link'] = $link;
708
709                                                 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
710                                                         $video = $link;
711                                                 }
712                                         }
713                                         if(trim($linkname) != "")
714                                                 $postvars['name'] = $linkname;
715                                 }
716
717                                 if(($b['private']) && ($toplevel)) {
718                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
719                                         if(count($allow_arr))
720                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
721                                         if(count($deny_arr))
722                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
723                                         $postvars['privacy'] .= '}';
724
725                                 }
726
727                                 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
728                                 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
729                                 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
730                                         $target = $post_to_page;
731                                 else
732                                         $target = "me";
733
734                                 if($reply) {
735                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
736                                 } else if (($video != "") or (($image == "") and ($link != ""))) {
737                                         // If it is a link to a video or a link without a preview picture then post it as a link
738                                         if ($video != "")
739                                                 $link = $video;
740
741                                         $postvars = array(
742                                                 'access_token' => $fb_token,
743                                                 'link' => $link,
744                                         );
745                                         if ($msg != $video)
746                                                 $postvars['message'] = $msg;
747
748                                         $url = 'https://graph.facebook.com/'.$target.'/links';
749                                 } else if (($link == "") and ($image != "")) {
750                                         // If it is only an image without a page link then post this image as a photo
751                                         $postvars = array(
752                                                 'access_token' => $fb_token,
753                                                 'url' => $image,
754                                         );
755                                         if ($msg != $image)
756                                                 $postvars['message'] = $msg;
757
758                                         $url = 'https://graph.facebook.com/'.$target.'/photos';
759                                 } else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
760                                         $url = 'https://graph.facebook.com/'.$target.'/feed';
761                                         if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
762                                                 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' .  $b['plink'] . '"}';
763                                 } else {
764                                         // if its only a message and a subject and the message is larger than 500 characters then post it as note
765                                         $postvars = array(
766                                                 'access_token' => $fb_token,
767                                                 'message' => bbcode($b['body'], false, false),
768                                                 'subject' => $b['title'],
769                                         );
770                                         $url = 'https://graph.facebook.com/'.$target.'/notes';
771                                 }
772
773                                 // Post to page?
774                                 if (!$reply and ($target != "me") and $page_access_token)
775                                         $postvars['access_token'] = $page_access_token;
776
777                                 logger('facebook: post to ' . $url);
778                                 logger('facebook: postvars: ' . print_r($postvars,true));
779
780                                 // "test_mode" prevents anything from actually being posted.
781                                 // Otherwise, let's do it.
782
783                                 if(! get_config('facebook','test_mode')) {
784                                         $x = post_url($url, $postvars);
785                                         logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
786
787                                         $retj = json_decode($x);
788                                         if($retj->id) {
789                                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
790                                                         dbesc('fb::' . $retj->id),
791                                                         intval($b['id'])
792                                                 );
793                                         }
794                                         else {
795                                                 if(! $likes) {
796                                                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
797                                                         require_once('include/queue_fn.php');
798                                                         add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
799                                                         notice( t('Facebook post failed. Queued for retry.') . EOL);
800                                                 }
801
802                                                 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
803                                                         logger('Facebook session has expired due to changed password.', LOGGER_DEBUG);
804
805                                                         $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
806                                                         if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
807                                                                 require_once('include/enotify.php');
808
809                                                                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']) );
810                                                                 notification(array(
811                                                                         'uid' => $b['uid'],
812                                                                         'type' => NOTIFY_SYSTEM,
813                                                                         'system_type' => 'facebook_connection_invalid',
814                                                                         'language'     => $r[0]['language'],
815                                                                         'to_name'      => $r[0]['username'],
816                                                                         'to_email'     => $r[0]['email'],
817                                                                         'source_name'  => t('Administrator'),
818                                                                         'source_link'  => $a->config["system"]["url"],
819                                                                         'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
820                                                                 ));
821
822                                                                 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
823                                                         } else logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
824                                                 }
825                                         }
826                                 }
827                         }
828                 }
829         }
830 }
831
832 /**
833  * @param App $app
834  * @param object $data
835  */
836 function fbpost_enotify(&$app, &$data) {
837         if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
838                 $data['itemlink'] = '/facebook';
839                 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
840                 $data['subject'] = t('Facebook connection became invalid');
841                 $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]");
842         }
843 }
844
845 /**
846  * @param App $a
847  * @param object $b
848  */
849 function fbpost_post_local(&$a,&$b) {
850
851         // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
852         // where we will discover it during background delivery.
853
854         // This can only be triggered by a local user posting to their own wall.
855
856         if((local_user()) && (local_user() == $b['uid'])) {
857
858                 $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
859                 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
860
861                 // if API is used, default to the chosen settings
862                 // but allow a specific override
863
864                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
865                         if(! x($_REQUEST,'facebook_enable'))
866                                 $fb_enable = 1;
867                 }
868
869                 if(! $fb_enable)
870                         return;
871
872                 if(strlen($b['postopts']))
873                         $b['postopts'] .= ',';
874                 $b['postopts'] .= 'facebook';
875         }
876 }
877
878
879 /**
880  * @param App $a
881  * @param object $b
882  */
883 function fbpost_queue_hook(&$a,&$b) {
884
885         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
886                 dbesc(NETWORK_FACEBOOK)
887         );
888         if(! count($qi))
889                 return;
890
891         require_once('include/queue_fn.php');
892
893         foreach($qi as $x) {
894                 if($x['network'] !== NETWORK_FACEBOOK)
895                         continue;
896
897                 logger('facebook_queue: run');
898
899                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
900                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
901                         intval($x['cid'])
902                 );
903                 if(! count($r))
904                         continue;
905
906                 $user = $r[0];
907
908                 $appid  = get_config('facebook', 'appid'  );
909                 $secret = get_config('facebook', 'appsecret' );
910
911                 if($appid && $secret) {
912                         $fb_post   = intval(get_pconfig($user['uid'],'facebook','post'));
913                         $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
914
915                         if($fb_post && $fb_token) {
916                                 logger('facebook_queue: able to post');
917                                 require_once('library/facebook.php');
918
919                                 $z = unserialize($x['content']);
920                                 $item = $z['item'];
921                                 $j = post_url($z['url'],$z['post']);
922
923                                 $retj = json_decode($j);
924                                 if($retj->id) {
925                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
926                                                 dbesc('fb::' . $retj->id),
927                                                 intval($item)
928                                         );
929                                         logger('facebook_queue: success: ' . $j); 
930                                         remove_queue_item($x['id']);
931                                 }
932                                 else {
933                                         logger('facebook_queue: failed: ' . $j);
934                                         update_queue_time($x['id']);
935                                 }
936                         }
937                 }
938         }
939 }
940
941
942 /**
943  * @return bool|string
944  */
945 function fbpost_get_app_access_token() {
946
947         $acc_token = get_config('facebook','app_access_token');
948
949         if ($acc_token !== false) return $acc_token;
950
951         $appid = get_config('facebook','appid');
952         $appsecret = get_config('facebook', 'appsecret');
953
954         if ($appid === false || $appsecret === false) {
955                 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
956                 return false;
957         }
958         logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
959         $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
960
961         if(strpos($x,'access_token=') !== false) {
962                 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
963
964                 $token = str_replace('access_token=', '', $x);
965                 if(strpos($token,'&') !== false)
966                         $token = substr($token,0,strpos($token,'&'));
967
968                 if ($token == "") {
969                         logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
970                         return false;
971                 }
972                 set_config('facebook','app_access_token',$token);
973                 return $token;
974         } else {
975                 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
976                 return false;
977         }
978 }
979
980 function fbpost_cron($a,$b) {
981         $last = get_config('facebook','last_poll');
982
983         $poll_interval = intval(get_config('facebook','poll_interval'));
984         if(! $poll_interval)
985                 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
986
987         if($last) {
988                 $next = $last + ($poll_interval * 60);
989                 if($next > time()) {
990                         logger('facebook: poll intervall not reached');
991                         return;
992                 }
993         }
994         logger('facebook: cron_start');
995
996         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
997         if(count($r)) {
998                 foreach($r as $rr) {
999                         logger('facebook: fetching for user '.$rr['uid']);
1000                         fbpost_fetchwall($a, $rr['uid']);
1001                 }
1002         }
1003
1004         logger('facebook: cron_end');
1005
1006         set_config('facebook','last_poll', time());
1007 }
1008
1009 function fbpost_fetchwall($a, $uid) {
1010         $access_token = get_pconfig($uid,'facebook','access_token');
1011         $post_to_page = get_pconfig($uid,'facebook','post_to_page');
1012         $lastcreated = get_pconfig($uid,'facebook','last_created');
1013
1014         if ((int)$post_to_page == 0)
1015                 $post_to_page = "me";
1016
1017         $url = "https://graph.facebook.com/".$post_to_page."/feed?access_token=".$access_token;
1018
1019         if ($lastcreated != "")
1020                 $url .= "&since=".urlencode($lastcreated);
1021
1022         $feed = fetch_url($url);
1023         $data = json_decode($feed);
1024         $items = array_reverse($data->data);
1025
1026         foreach ($items as $item) {
1027                 if ($item->created_time > $lastcreated)
1028                         $lastcreated = $item->created_time;
1029
1030                 if ($item->application->id == get_config('facebook','appid'))
1031                         continue;
1032
1033                 if(isset($item->privacy) && ($item->privacy->value !== 'EVERYONE') && ($item->privacy->value !== ''))
1034                         continue;
1035
1036                 $_SESSION["authenticated"] = true;
1037                 $_SESSION["uid"] = $uid;
1038
1039                 $_REQUEST["type"] = "wall";
1040                 $_REQUEST["api_source"] = true;
1041                 $_REQUEST["profile_uid"] = $uid;
1042                 $_REQUEST["source"] = "Facebook";
1043
1044                 $_REQUEST["body"] = (isset($item->message) ? escape_tags($item->message) : '');
1045
1046                 if(isset($item->name) and isset($item->link))
1047                         $_REQUEST["body"] .= "\n\n[bookmark=".$item->link."]".$item->name."[/bookmark]";
1048                 elseif (isset($item->name))
1049                         $_REQUEST["body"] .= "\n\n[b]" . $item->name."[/b]";
1050
1051                 /*if(isset($item->caption)) {
1052                         if(!isset($item->name) and isset($item->link))
1053                                 $_REQUEST["body"] .= "\n\n[bookmark=".$item->link."]".$item->caption."[/bookmark]";
1054                         //else
1055                         //      $_REQUEST["body"] .= "[i]" . $item->caption."[/i]\n";
1056                         }
1057
1058                         if(!isset($item->caption) and !isset($item->name)) {
1059                                 if (isset($item->link))
1060                                         $_REQUEST["body"] .= "\n[url]".$item->link."[/url]\n";
1061                                 else
1062                                         $_REQUEST["body"] .= "\n";
1063                 }*/
1064
1065                 $quote = "";
1066                 if(isset($item->description) and ($item->type != "photo"))
1067                         $quote = $item->description;
1068
1069                 if(isset($item->caption) and ($item->type == "photo"))
1070                         $quote = $item->caption;
1071
1072                 //if (isset($item->properties))
1073                 //      foreach ($item->properties as $property)
1074                 //              $quote .= "\n".$property->name.": [url=".$property->href."]".$property->text."[/url]";
1075
1076                 if ($quote)
1077                         $_REQUEST["body"] .= "\n[quote]".$quote."[/quote]";
1078
1079                 // Only import the picture when the message is no video
1080                 // oembed display a picture of the video as well
1081                 //if ($item->type != "video") {
1082                 if (($item->type != "video") and ($item->type != "photo")) {
1083                         if(isset($item->picture) && isset($item->link))
1084                                 $_REQUEST["body"] .= "\n".'[url='.$item->link.'][img]'.fpost_cleanpicture($item->picture).'[/img][/url]';
1085                         else {
1086                                 if (isset($item->picture))
1087                                         $_REQUEST["body"] .= "\n".'[img]'.fpost_cleanpicture($item->picture).'[/img]';
1088                                 // if just a link, it may be a wall photo - check
1089                                 if(isset($item->link))
1090                                         $_REQUEST["body"] .= fbpost_get_photo($uid,$item->link);
1091                         }
1092                 }
1093
1094                 /*if (($datarray['app'] == "Events") and isset($item->actions))
1095                         foreach ($item->actions as $action)
1096                                 if ($action->name == "View")
1097                                         $_REQUEST["body"] .= " [url=".$action->link."]".$item->story."[/url]";
1098                 */
1099
1100                 if(trim($_REQUEST["body"]) == '') {
1101                         logger('facebook: empty body '.$item->id.' '.print_r($item, true));
1102                         continue;
1103                 }
1104
1105                 $_REQUEST["body"] = trim($_REQUEST["body"]);
1106
1107                 if (isset($item->place)) {
1108                         if ($item->place->name or $item->place->location->street or
1109                                 $item->place->location->city or $item->place->location->country) {
1110                                 $_REQUEST["location"] = '';
1111                                 if ($item->place->name)
1112                                         $_REQUEST["location"] .= $item->place->name;
1113                                 if ($item->place->location->street)
1114                                         $_REQUEST["location"] .= " ".$item->place->location->street;
1115                                 if ($item->place->location->city)
1116                                         $_REQUEST["location"] .= " ".$item->place->location->city;
1117                                 if ($item->place->location->country)
1118                                         $_REQUEST["location"] .= " ".$item->place->location->country;
1119
1120                                 $_REQUEST["location"] = trim($_REQUEST["location"]);
1121                         }
1122                         if ($item->place->location->latitude and $item->place->location->longitude)
1123                                 $_REQUEST["coord"] = substr($item->place->location->latitude, 0, 8)
1124                                                 .' '.substr($item->place->location->longitude, 0, 8);
1125                 }
1126
1127                 //print_r($_REQUEST);
1128                 logger('facebook: posting for user '.$uid);
1129
1130                 require_once('mod/item.php');
1131                 item_post($a);
1132         }
1133
1134         set_pconfig($uid,'facebook','last_created', $lastcreated);
1135 }
1136
1137 function fbpost_get_photo($uid,$link) {
1138         $access_token = get_pconfig($uid,'facebook','access_token');
1139         if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1140                 return "";
1141
1142         $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1143         if($ret)
1144                 $photo_id = $match[1];
1145         else
1146                 return "";
1147
1148         $x = fetch_url('https://graph.facebook.com/'.$photo_id.'?access_token='.$access_token);
1149         $j = json_decode($x);
1150         if($j->picture)
1151                 return "\n\n".'[url='.$link.'][img]'.fpost_cleanpicture($j->picture).'[/img][/url]';
1152
1153         return "";
1154 }
1155
1156 function fpost_cleanpicture($image) {
1157
1158         if (strpos($image, ".fbcdn.net/") and (substr($image, -6) == "_s.jpg"))
1159                 $image = substr($image, 0, -6)."_n.jpg";
1160
1161         $queryvar = fbpost_parse_query($image);
1162         if ($queryvar['url'] != "")
1163                 $image = urldecode($queryvar['url']);
1164
1165         return $image;
1166 }
1167
1168 function fbpost_parse_query($var) {
1169         /**
1170          *  Use this function to parse out the query array element from
1171          *  the output of parse_url().
1172         */
1173         $var  = parse_url($var, PHP_URL_QUERY);
1174         $var  = html_entity_decode($var);
1175         $var  = explode('&', $var);
1176         $arr  = array();
1177
1178         foreach($var as $val) {
1179                 $x          = explode('=', $val);
1180                 $arr[$x[0]] = $x[1];
1181         }
1182
1183         unset($val, $x, $var);
1184         return $arr;
1185 }