]> git.mxchange.org Git - friendica-addons.git/blob - fbpost/fbpost.php
fbpost: videos are now posted as links
[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
26 require_once('include/security.php');
27
28 function fbpost_install() {
29         register_hook('post_local',       'addon/fbpost/fbpost.php', 'fbpost_post_local');
30         register_hook('notifier_normal',  'addon/fbpost/fbpost.php', 'fbpost_post_hook');
31         register_hook('jot_networks',     'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
32         register_hook('connector_settings',  'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
33         register_hook('enotify',          'addon/fbpost/fbpost.php', 'fbpost_enotify');
34         register_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
35 }
36
37
38 function fbpost_uninstall() {
39         unregister_hook('post_local',       'addon/fbpost/fbpost.php', 'fbpost_post_local');
40         unregister_hook('notifier_normal',  'addon/fbpost/fbpost.php', 'fbpost_post_hook');
41         unregister_hook('jot_networks',     'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
42         unregister_hook('connector_settings',  'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
43         unregister_hook('enotify',          'addon/fbpost/fbpost.php', 'fbpost_enotify');
44         unregister_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
45
46
47 }
48
49
50 /* declare the fbpost_module function so that /fbpost url requests will land here */
51
52 function fbpost_module() {}
53
54
55
56 // If a->argv[1] is a nickname, this is a callback from Facebook oauth requests.
57 // If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API
58
59 /**
60  * @param App $a
61  */
62 function fbpost_init(&$a) {
63
64         if($a->argc != 2)
65                 return;
66
67         $nick = $a->argv[1];
68
69         if(strlen($nick))
70                 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
71                                 dbesc($nick)
72                 );
73         if(!(isset($r) && count($r)))
74                 return;
75
76         $uid           = $r[0]['uid'];
77         $auth_code     = (x($_GET, 'code') ? $_GET['code'] : '');
78         $error         = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
79
80
81         if($error)
82                 logger('fbpost_init: Error: ' . $error);
83
84         if($auth_code && $uid) {
85
86                 $appid = get_config('facebook','appid');
87                 $appsecret = get_config('facebook', 'appsecret');
88
89                 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
90                         . $appid . '&client_secret=' . $appsecret . '&redirect_uri='
91                         . urlencode($a->get_baseurl() . '/fbpost/' . $nick)
92                         . '&code=' . $auth_code);
93
94                 logger('fbpost_init: returned access token: ' . $x, LOGGER_DATA);
95
96                 if(strpos($x,'access_token=') !== false) {
97                         $token = str_replace('access_token=', '', $x);
98                         if(strpos($token,'&') !== false)
99                                 $token = substr($token,0,strpos($token,'&'));
100                         set_pconfig($uid,'facebook','access_token',$token);
101                         set_pconfig($uid,'facebook','post','1');
102                         fbpost_get_self($uid);
103                 }
104
105         }
106
107 }
108
109
110 /**
111  * @param int $uid
112  */
113 function fbpost_get_self($uid) {
114         $access_token = get_pconfig($uid,'facebook','access_token');
115         if(! $access_token)
116                 return;
117         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
118         if($s) {
119                 $j = json_decode($s);
120                 set_pconfig($uid,'facebook','self_id',(string) $j->id);
121         }
122 }
123
124
125 // This is the POST method to the facebook settings page
126 // Content is posted to Facebook in the function facebook_post_hook()
127
128 /**
129  * @param App $a
130  */
131 function fbpost_post(&$a) {
132
133         $uid = local_user();
134         if($uid){
135
136
137                 $fb_limited = get_config('facebook','crestrict');
138
139
140                 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
141                 set_pconfig($uid,'facebook','post_by_default', $value);
142
143                 $value = ((x($_POST,'suppress_view_on_friendica')) ? intval($_POST['suppress_view_on_friendica']) : 0);
144                 set_pconfig($uid,'facebook','suppress_view_on_friendica', $value);
145
146                 $value = ((x($_POST,'post_to_page')) ? $_POST['post_to_page'] : "0-0");
147                 $values = explode("-", $value);
148                 set_pconfig($uid,'facebook','post_to_page', $values[0]);
149                 set_pconfig($uid,'facebook','page_access_token', $values[1]);
150
151                 info( t('Settings updated.') . EOL);
152         }
153
154         return;
155 }
156
157 // Facebook settings form
158
159 /**
160  * @param App $a
161  * @return string
162  */
163 function fbpost_content(&$a) {
164
165         if(! local_user()) {
166                 notice( t('Permission denied.') . EOL);
167                 return '';
168         }
169
170
171         if(! service_class_allows(local_user(),'facebook_connect')) {
172                 notice( t('Permission denied.') . EOL);
173                 return upgrade_bool_message();
174         }
175
176
177         if($a->argc > 1 && $a->argv[1] === 'remove') {
178                 del_pconfig(local_user(),'facebook','post');
179                 info( t('Facebook Post disabled') . EOL);
180         }
181
182         $o = '';
183         
184         $fb_installed = false;
185         if (get_pconfig(local_user(),'facebook','post')) {
186                 $access_token = get_pconfig(local_user(),'facebook','access_token');
187                 if ($access_token) {
188                         $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
189                         if($s) {
190                                 $j = json_decode($s);
191                                 if (isset($j->data)) $fb_installed = true;
192                         }
193                 }
194         }
195         
196         $appid = get_config('facebook','appid');
197
198         if(! $appid) {
199                 notice( t('Facebook API key is missing.') . EOL);
200                 return '';
201         }
202
203         $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
204                 . $a->get_baseurl() . '/addon/fbpost/fbpost.css' . '" media="all" />' . "\r\n";
205
206         $o .= '<h3>' . t('Facebook Post') . '</h3>';
207
208         if(! $fb_installed) { 
209                 $o .= '<div id="fbpost-enable-wrapper">';
210
211                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
212                         . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=publish_stream,manage_pages,photo_upload,user_groups,offline_access">' . t('Install Facebook Post connector for this account.') . '</a>';
213                 $o .= '</div>';
214         }
215
216         if($fb_installed) {
217                 $o .= '<div id="fbpost-disable-wrapper">';
218
219                 $o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
220
221                 $o .= '<div id="fbpost-enable-wrapper">';
222
223                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
224                         . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=publish_stream,manage_pages,photo_upload,user_groups,offline_access">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
225                 $o .= '</div>';
226
227                 $o .= '<div id="fbpost-post-default-form">';
228                 $o .= '<form action="fbpost" method="post" >';
229                 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
230                 $checked = (($post_by_default) ? ' checked="checked" ' : '');
231                 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
232
233                 $suppress_view_on_friendica = get_pconfig(local_user(),'facebook','suppress_view_on_friendica');
234                 $checked = (($suppress_view_on_friendica) ? ' checked="checked" ' : '');
235                 $o .= '<input type="checkbox" name="suppress_view_on_friendica" value="1"' . $checked . '/>' . ' ' . t('Suppress "View on friendica"') . EOL;
236
237                 // List all pages
238                 $post_to_page = get_pconfig(local_user(),'facebook','post_to_page');
239                 $page_access_token = get_pconfig(local_user(),'facebook','page_access_token');
240                 $fb_token  = get_pconfig($a->user['uid'],'facebook','access_token');
241                 $url = 'https://graph.facebook.com/me/accounts';
242                 $x = file_get_contents($url."?access_token=".$fb_token);
243                 $accounts = json_decode($x);
244
245                 $o .= t("Post to page/group:")."<select name='post_to_page'>";
246                 if (intval($post_to_page) == 0)
247                         $o .= "<option value='0-0' selected>".t('None')."</option>";
248                 else
249                         $o .= "<option value='0-0'>".t('None')."</option>";
250
251                 foreach($accounts->data as $account) {
252                         if (is_array($account->perms))
253                                 if ($post_to_page == $account->id)
254                                         $o .= "<option value='".$account->id."-".$account->access_token."' selected>".$account->name."</option>";
255                                 else
256                                         $o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
257                 }
258
259                 $url = 'https://graph.facebook.com/me/groups';
260                 $x = file_get_contents($url."?access_token=".$fb_token);
261                 $groups = json_decode($x);
262
263                 foreach($groups->data as $group) {
264                         if ($post_to_page == $group->id)
265                                 $o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
266                         else
267                                 $o .= "<option value='".$group->id."-0'>".$group->name."</option>";
268                 }
269
270                 $o .= "</select>";
271
272                 $o .= '<p><input type="submit" name="submit" value="' . t('Submit') . '" /></form></div>';
273
274         }
275
276         return $o;
277 }
278
279 /**
280  * @param App $a
281  * @param null|object $b
282  */
283 function fbpost_plugin_settings(&$a,&$b) {
284
285         $b .= '<div class="settings-block">';
286         $b .= '<h3>' . t('Facebook') . '</h3>';
287         $b .= '<a href="fbpost">' . t('Facebook Post Settings') . '</a><br />';
288         $b .= '</div>';
289
290 }
291
292
293 /**
294  * @param App $a
295  * @param null|object $o
296  */
297 function fbpost_plugin_admin(&$a, &$o){
298
299
300         $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
301         
302         $o .= '<h4>' . t('Facebook API Key') . '</h4>';
303         
304         $appid  = get_config('facebook', 'appid'  );
305         $appsecret = get_config('facebook', 'appsecret' );
306         
307         $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
308         $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
309         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>');
310         
311         $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;">';
312         $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;">';
313
314         $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
315         
316 }
317
318 /**
319  * @param App $a
320  */
321
322 function fbpost_plugin_admin_post(&$a){
323         check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
324         
325         if (x($_REQUEST,'fb_save_keys')) {
326                 set_config('facebook', 'appid', $_REQUEST['appid']);
327                 set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
328
329                 info(t('The new values have been saved.'));
330         }
331
332 }
333
334 /**
335  * @param App $a
336  * @param object $b
337  * @return mixed
338  */
339 function fbpost_jot_nets(&$a,&$b) {
340         if(! local_user())
341                 return;
342
343         $fb_post = get_pconfig(local_user(),'facebook','post');
344         if(intval($fb_post) == 1) {
345                 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
346                 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
347                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> ' 
348                         . t('Post to Facebook') . '</div>';     
349         }
350 }
351
352
353 /**
354  * @param App $a
355  * @param object $b
356  * @return mixed
357  */
358 function fbpost_post_hook(&$a,&$b) {
359
360
361         if($b['deleted'] || ($b['created'] !== $b['edited']))
362                 return;
363
364         /**
365          * Post to Facebook stream
366          */
367
368         require_once('include/group.php');
369         require_once('include/html2plain.php');
370
371         logger('Facebook post');
372
373         $reply = false;
374         $likes = false;
375
376         $deny_arr = array();
377         $allow_arr = array();
378
379         $toplevel = (($b['id'] == $b['parent']) ? true : false);
380
381
382         $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
383
384         if((! $toplevel) && ($linking)) {
385                 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
386                         intval($b['parent']),
387                         intval($b['uid'])
388                 );
389                 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
390                         $reply = substr($r[0]['uri'],4);
391                 elseif(count($r) && substr($r[0]['extid'],0,4) === 'fb::')
392                         $reply = substr($r[0]['extid'],4);
393                 else
394                         return;
395
396                 $u = q("SELECT * FROM user where uid = %d limit 1",
397                         intval($b['uid'])
398                 );
399                 if(! count($u))
400                         return;
401
402                 // only accept comments from the item owner. Other contacts are unknown to FB.
403
404                 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
405                         return;
406
407
408                 logger('facebook reply id=' . $reply);
409         }
410
411         if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
412
413                 if($b['private'] && $reply === false) {
414                         $allow_people = expand_acl($b['allow_cid']);
415                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
416                         $deny_people  = expand_acl($b['deny_cid']);
417                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
418
419                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
420                         $deny = array_unique(array_merge($deny_people,$deny_groups));
421
422                         $allow_str = dbesc(implode(', ',$recipients));
423                         if($allow_str) {
424                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'"); 
425                                 if(count($r))
426                                         foreach($r as $rr)
427                                                 $allow_arr[] = $rr['notify'];
428                         }
429
430                         $deny_str = dbesc(implode(', ',$deny));
431                         if($deny_str) {
432                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'"); 
433                                 if(count($r))
434                                         foreach($r as $rr)
435                                                 $deny_arr[] = $rr['notify'];
436                         }
437
438                         if(count($deny_arr) && (! count($allow_arr))) {
439
440                                 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
441                                 // This might cause the post to be open to public on Facebook, but only to selected members
442                                 // on another network. Since this could potentially leak a post to somebody who was denied, 
443                                 // we will skip posting it to Facebook with a slightly vague but relevant message that will 
444                                 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
445
446                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
447                                 return;
448                         }
449
450
451                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
452
453                         if((! count($allow_arr)) && (! count($deny_arr)))
454                                 return;
455                 }
456
457                 if($b['verb'] == ACTIVITY_LIKE)
458                         $likes = true;
459
460
461                 $appid  = get_config('facebook', 'appid'  );
462                 $secret = get_config('facebook', 'appsecret' );
463
464                 if($appid && $secret) {
465
466                         logger('facebook: have appid+secret');
467
468                         $fb_token  = get_pconfig($b['uid'],'facebook','access_token');
469
470
471                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
472                         // or it's a private message with facebook participants
473                         // or it's a reply or likes action to an existing facebook post
474
475                         if($fb_token && ($toplevel || $b['private'] || $reply)) {
476                                 logger('facebook: able to post');
477                                 require_once('library/facebook.php');
478                                 require_once('include/bbcode.php');
479
480                                 $msg = $b['body'];
481
482                                 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
483
484                                 // make links readable before we strip the code
485
486                                 // unless it's a dislike - just send the text as a comment
487
488                                 // if($b['verb'] == ACTIVITY_DISLIKE)
489                                 //      $msg = trim(strip_tags(bbcode($msg)));
490
491                                 // Old code
492                                 /*$search_str = $a->get_baseurl() . '/search';
493
494                                 if(preg_match("/\[url=(.*?)\](.*?)\[\/url\]/is",$msg,$matches)) {
495
496                                         // don't use hashtags for message link
497
498                                         if(strpos($matches[2],$search_str) === false) {
499                                                 $link = $matches[1];
500                                                 if(substr($matches[2],0,5) != '[img]')
501                                                         $linkname = $matches[2];
502                                         }
503                                 }
504
505                                 // strip tag links to avoid link clutter, this really should be 
506                                 // configurable because we're losing information
507
508                                 $msg = preg_replace("/\#\[url=(.*?)\](.*?)\[\/url\]/is",'#$2',$msg);
509
510                                 // provide the link separately for normal links
511                                 $msg = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is",'$2 $1',$msg);
512
513                                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$msg,$matches))
514                                         $image = $matches[1];
515
516                                 $msg = preg_replace("/\[img\](.*?)\[\/img\]/is", t('Image: ') . '$1', $msg);
517
518                                 if((strpos($link,z_root()) !== false) && (! $image))
519                                         $image = $a->get_baseurl() . '/images/friendica-64.jpg';
520
521                                 $msg = trim(strip_tags(bbcode($msg)));*/
522
523                                 // New code
524
525                                 // Looking for the first image
526                                 $image = '';
527                                 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
528                                         $image = $matches[3];
529
530                                 if ($image == '')
531                                         if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
532                                                 $image = $matches[1];
533
534                                 // When saved into the database the content is sent through htmlspecialchars
535                                 // That means that we have to decode all image-urls
536                                 $image = htmlspecialchars_decode($image);
537
538                                 // Checking for a bookmark element
539                                 $body = $b['body'];
540                                 if (strpos($body, "[bookmark") !== false) {
541                                         // splitting the text in two parts:
542                                         // before and after the bookmark
543                                         $pos = strpos($body, "[bookmark");
544                                         $body1 = substr($body, 0, $pos);
545                                         $body2 = substr($body, $pos);
546
547                                         // Removing the bookmark and all quotes after the bookmark
548                                         // they are mostly only the content after the bookmark.
549                                         $body2 = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'',$body2);
550                                         $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
551                                         $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
552
553                                         $body = $body1.$body2;
554                                 }
555
556                                 // At first convert the text to html
557                                 $html = bbcode($body, false, false);
558
559                                 // Then convert it to plain text
560                                 $msg = trim($b['title']." \n\n".html2plain($html, 0, true));
561                                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
562
563                                 // Removing multiple newlines
564                                 while (strpos($msg, "\n\n\n") !== false)
565                                         $msg = str_replace("\n\n\n", "\n\n", $msg);
566
567                                 // add any attachments as text urls
568                                 $arr = explode(',',$b['attach']);
569
570                                 if(count($arr)) {
571                                         $msg .= "\n";
572                                         foreach($arr as $r) {
573                                                 $matches = false;
574                                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
575                                                 if($cnt) {
576                                                         $msg .= "\n".$matches[1];
577                                                 }
578                                         }
579                                 }
580
581                                 $link = '';
582                                 $linkname = '';
583                                 // look for bookmark-bbcode and handle it with priority
584                                 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
585                                         $link = $matches[1];
586                                         $linkname = $matches[2];
587                                 }
588
589                                 // If there is no bookmark element then take the first link
590                                 if ($link == '') {
591                                         $links = collecturls($html);
592                                         if (sizeof($links) > 0) {
593                                                 reset($links);
594                                                 $link = current($links);
595                                         }
596                                 }
597
598                                 // Remove trailing and leading spaces
599                                 $msg = trim($msg);
600
601
602                                 // Fallback - if message is empty
603                                 if(!strlen($msg))
604                                         $msg = $linkname;
605
606                                 if(!strlen($msg))
607                                         $msg = $link;
608
609                                 if(!strlen($msg))
610                                         $msg = $image;
611
612                                 // If there is nothing to post then exit
613                                 if(!strlen($msg))
614                                         return;
615
616                                 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
617
618                                 $video = "";
619
620                                 if($likes) {
621                                         $postvars = array('access_token' => $fb_token);
622                                 } else {
623                                         // message, picture, link, name, caption, description, source, place, tags
624                                         $postvars = array(
625                                                 'access_token' => $fb_token,
626                                                 'message' => $msg
627                                         );
628                                         if(trim($image) != "") {
629                                                 $postvars['picture'] = $image;
630                                         }
631                                         if(trim($link) != "") {
632                                                 $postvars['link'] = $link;
633
634                                                 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
635                                                         $video = $link;
636                                                 }
637                                         }
638                                         if(trim($linkname) != "")
639                                                 $postvars['name'] = $linkname;
640                                 }
641
642                                 if(($b['private']) && ($toplevel)) {
643                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
644                                         if(count($allow_arr))
645                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
646                                         if(count($deny_arr))
647                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
648                                         $postvars['privacy'] .= '}';
649
650                                 }
651
652                                 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
653                                 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
654                                 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
655                                         $target = $post_to_page;
656                                 else
657                                         $target = "me";
658
659                                 if($reply) {
660                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
661                                 } else if (($video != "")) {
662                                         // If it is a link to a video then post it as a link
663                                         $postvars = array(
664                                                 'access_token' => $fb_token,
665                                                 'link' => $video,
666                                         );
667                                         if ($msg != $video)
668                                                 $postvars['message'] = $msg;
669
670                                         $url = 'https://graph.facebook.com/'.$target.'/links';
671                                 } else if (($link == "") and ($image != "")) {
672                                         // If it is only an image without a page link then post this image as a photo
673                                         $postvars = array(
674                                                 'access_token' => $fb_token,
675                                                 'url' => $image,
676                                         );
677                                         if ($msg != $image)
678                                                 $postvars['message'] = $msg;
679
680                                         $url = 'https://graph.facebook.com/'.$target.'/photos';
681                                 } else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500) or ($target != "me")) {
682                                         $url = 'https://graph.facebook.com/'.$target.'/feed';
683                                         if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
684                                                 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' .  $b['plink'] . '"}';
685                                 } else {
686                                         // if its only a message and a subject and the message is larger than 500 characters then post it as note
687                                         $postvars = array(
688                                                 'access_token' => $fb_token,
689                                                 'message' => bbcode($b['body'], false, false),
690                                                 'subject' => $b['title'],
691                                         );
692                                         $url = 'https://graph.facebook.com/me/notes';
693                                 }
694
695                                 // Post to page?
696                                 if (!$reply and ($target != "me") and $page_access_token)
697                                         $postvars['access_token'] = $page_access_token;
698
699                                 logger('facebook: post to ' . $url);
700                                 logger('facebook: postvars: ' . print_r($postvars,true));
701
702                                 // "test_mode" prevents anything from actually being posted.
703                                 // Otherwise, let's do it.
704
705                                 if(! get_config('facebook','test_mode')) {
706                                         $x = post_url($url, $postvars);
707                                         logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
708
709                                         $retj = json_decode($x);
710                                         if($retj->id) {
711                                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
712                                                         dbesc('fb::' . $retj->id),
713                                                         intval($b['id'])
714                                                 );
715                                         }
716                                         else {
717                                                 if(! $likes) {
718                                                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
719                                                         require_once('include/queue_fn.php');
720                                                         add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
721                                                         notice( t('Facebook post failed. Queued for retry.') . EOL);
722                                                 }
723
724                                                 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
725                                                         logger('Facebook session has expired due to changed password.', LOGGER_DEBUG);
726
727                                                         $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
728                                                         if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
729                                                                 require_once('include/enotify.php');
730
731                                                                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']) );
732                                                                 notification(array(
733                                                                         'uid' => $b['uid'],
734                                                                         'type' => NOTIFY_SYSTEM,
735                                                                         'system_type' => 'facebook_connection_invalid',
736                                                                         'language'     => $r[0]['language'],
737                                                                         'to_name'      => $r[0]['username'],
738                                                                         'to_email'     => $r[0]['email'],
739                                                                         'source_name'  => t('Administrator'),
740                                                                         'source_link'  => $a->config["system"]["url"],
741                                                                         'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
742                                                                 ));
743
744                                                                 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
745                                                         } else logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
746                                                 }
747                                         }
748                                 }
749                         }
750                 }
751         }
752 }
753
754 /**
755  * @param App $app
756  * @param object $data
757  */
758 function fbpost_enotify(&$app, &$data) {
759         if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
760                 $data['itemlink'] = '/facebook';
761                 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
762                 $data['subject'] = t('Facebook connection became invalid');
763                 $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]");
764         }
765 }
766
767 /**
768  * @param App $a
769  * @param object $b
770  */
771 function fbpost_post_local(&$a,&$b) {
772
773         // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
774         // where we will discover it during background delivery.
775
776         // This can only be triggered by a local user posting to their own wall.
777
778         if((local_user()) && (local_user() == $b['uid'])) {
779
780                 $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
781                 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
782
783                 // if API is used, default to the chosen settings
784                 // but allow a specific override
785
786                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
787                         if(! x($_REQUEST,'facebook_enable'))
788                                 $fb_enable = 1;
789                 }
790
791                 if(! $fb_enable)
792                         return;
793
794                 if(strlen($b['postopts']))
795                         $b['postopts'] .= ',';
796                 $b['postopts'] .= 'facebook';
797         }
798 }
799
800
801 /**
802  * @param App $a
803  * @param object $b
804  */
805 function fbpost_queue_hook(&$a,&$b) {
806
807         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
808                 dbesc(NETWORK_FACEBOOK)
809         );
810         if(! count($qi))
811                 return;
812
813         require_once('include/queue_fn.php');
814
815         foreach($qi as $x) {
816                 if($x['network'] !== NETWORK_FACEBOOK)
817                         continue;
818
819                 logger('facebook_queue: run');
820
821                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
822                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
823                         intval($x['cid'])
824                 );
825                 if(! count($r))
826                         continue;
827
828                 $user = $r[0];
829
830                 $appid  = get_config('facebook', 'appid'  );
831                 $secret = get_config('facebook', 'appsecret' );
832
833                 if($appid && $secret) {
834                         $fb_post   = intval(get_pconfig($user['uid'],'facebook','post'));
835                         $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
836
837                         if($fb_post && $fb_token) {
838                                 logger('facebook_queue: able to post');
839                                 require_once('library/facebook.php');
840
841                                 $z = unserialize($x['content']);
842                                 $item = $z['item'];
843                                 $j = post_url($z['url'],$z['post']);
844
845                                 $retj = json_decode($j);
846                                 if($retj->id) {
847                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
848                                                 dbesc('fb::' . $retj->id),
849                                                 intval($item)
850                                         );
851                                         logger('facebook_queue: success: ' . $j); 
852                                         remove_queue_item($x['id']);
853                                 }
854                                 else {
855                                         logger('facebook_queue: failed: ' . $j);
856                                         update_queue_time($x['id']);
857                                 }
858                         }
859                 }
860         }
861 }
862
863
864 /**
865  * @return bool|string
866  */
867 function fbpost_get_app_access_token() {
868         
869         $acc_token = get_config('facebook','app_access_token');
870         
871         if ($acc_token !== false) return $acc_token;
872         
873         $appid = get_config('facebook','appid');
874         $appsecret = get_config('facebook', 'appsecret');
875         
876         if ($appid === false || $appsecret === false) {
877                 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
878                 return false;
879         }
880         logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
881         $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
882         
883         if(strpos($x,'access_token=') !== false) {
884                 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
885         
886                 $token = str_replace('access_token=', '', $x);
887                 if(strpos($token,'&') !== false)
888                         $token = substr($token,0,strpos($token,'&'));
889                 
890                 if ($token == "") {
891                         logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
892                         return false;
893                 }
894                 set_config('facebook','app_access_token',$token);
895                 return $token;
896         } else {
897                 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
898                 return false;
899         }
900 }
901