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