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