]> git.mxchange.org Git - friendica-addons.git/blob - fbpost/fbpost.php
Preparations for shared posts
[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 function fbpost_ShareAttributes($match) {
353
354         $attributes = $match[1];
355
356         $author = "";
357         preg_match("/author='(.*?)'/ism", $attributes, $matches);
358         if ($matches[1] != "")
359                 $author = $matches[1];
360
361         preg_match('/author="(.*?)"/ism', $attributes, $matches);
362         if ($matches[1] != "")
363                 $author = $matches[1];
364
365         $headline = '<div class="shared_header">';
366
367         $headline .= sprintf(t('%s:'), $author);
368
369         $headline .= "</div>";
370
371         $text = "<br />".$headline."</strong><blockquote>".$match[2]."</blockquote>";
372
373         return($text);
374 }
375
376
377 /**
378  * @param App $a
379  * @param object $b
380  * @return mixed
381  */
382 function fbpost_post_hook(&$a,&$b) {
383
384
385         if($b['deleted'] || ($b['created'] !== $b['edited']))
386                 return;
387
388         /**
389          * Post to Facebook stream
390          */
391
392         require_once('include/group.php');
393         require_once('include/html2plain.php');
394
395         logger('Facebook post');
396
397         $reply = false;
398         $likes = false;
399
400         $deny_arr = array();
401         $allow_arr = array();
402
403         $toplevel = (($b['id'] == $b['parent']) ? true : false);
404
405
406         $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
407
408         if((! $toplevel) && ($linking)) {
409                 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
410                         intval($b['parent']),
411                         intval($b['uid'])
412                 );
413                 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
414                         $reply = substr($r[0]['uri'],4);
415                 elseif(count($r) && substr($r[0]['extid'],0,4) === 'fb::')
416                         $reply = substr($r[0]['extid'],4);
417                 else
418                         return;
419
420                 $u = q("SELECT * FROM user where uid = %d limit 1",
421                         intval($b['uid'])
422                 );
423                 if(! count($u))
424                         return;
425
426                 // only accept comments from the item owner. Other contacts are unknown to FB.
427
428                 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
429                         return;
430
431
432                 logger('facebook reply id=' . $reply);
433         }
434
435         if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
436
437                 if($b['private'] && $reply === false) {
438                         $allow_people = expand_acl($b['allow_cid']);
439                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
440                         $deny_people  = expand_acl($b['deny_cid']);
441                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
442
443                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
444                         $deny = array_unique(array_merge($deny_people,$deny_groups));
445
446                         $allow_str = dbesc(implode(', ',$recipients));
447                         if($allow_str) {
448                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'"); 
449                                 if(count($r))
450                                         foreach($r as $rr)
451                                                 $allow_arr[] = $rr['notify'];
452                         }
453
454                         $deny_str = dbesc(implode(', ',$deny));
455                         if($deny_str) {
456                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'"); 
457                                 if(count($r))
458                                         foreach($r as $rr)
459                                                 $deny_arr[] = $rr['notify'];
460                         }
461
462                         if(count($deny_arr) && (! count($allow_arr))) {
463
464                                 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
465                                 // This might cause the post to be open to public on Facebook, but only to selected members
466                                 // on another network. Since this could potentially leak a post to somebody who was denied, 
467                                 // we will skip posting it to Facebook with a slightly vague but relevant message that will 
468                                 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
469
470                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
471                                 return;
472                         }
473
474
475                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
476
477                         if((! count($allow_arr)) && (! count($deny_arr)))
478                                 return;
479                 }
480
481                 if($b['verb'] == ACTIVITY_LIKE)
482                         $likes = true;
483
484
485                 $appid  = get_config('facebook', 'appid'  );
486                 $secret = get_config('facebook', 'appsecret' );
487
488                 if($appid && $secret) {
489
490                         logger('facebook: have appid+secret');
491
492                         $fb_token  = get_pconfig($b['uid'],'facebook','access_token');
493
494
495                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
496                         // or it's a private message with facebook participants
497                         // or it's a reply or likes action to an existing facebook post
498
499                         if($fb_token && ($toplevel || $b['private'] || $reply)) {
500                                 logger('facebook: able to post');
501                                 require_once('library/facebook.php');
502                                 require_once('include/bbcode.php');
503
504                                 $msg = $b['body'];
505
506                                 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
507
508                                 // make links readable before we strip the code
509
510                                 // unless it's a dislike - just send the text as a comment
511
512                                 // if($b['verb'] == ACTIVITY_DISLIKE)
513                                 //      $msg = trim(strip_tags(bbcode($msg)));
514
515                                 // Old code
516                                 /*$search_str = $a->get_baseurl() . '/search';
517
518                                 if(preg_match("/\[url=(.*?)\](.*?)\[\/url\]/is",$msg,$matches)) {
519
520                                         // don't use hashtags for message link
521
522                                         if(strpos($matches[2],$search_str) === false) {
523                                                 $link = $matches[1];
524                                                 if(substr($matches[2],0,5) != '[img]')
525                                                         $linkname = $matches[2];
526                                         }
527                                 }
528
529                                 // strip tag links to avoid link clutter, this really should be 
530                                 // configurable because we're losing information
531
532                                 $msg = preg_replace("/\#\[url=(.*?)\](.*?)\[\/url\]/is",'#$2',$msg);
533
534                                 // provide the link separately for normal links
535                                 $msg = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is",'$2 $1',$msg);
536
537                                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$msg,$matches))
538                                         $image = $matches[1];
539
540                                 $msg = preg_replace("/\[img\](.*?)\[\/img\]/is", t('Image: ') . '$1', $msg);
541
542                                 if((strpos($link,z_root()) !== false) && (! $image))
543                                         $image = $a->get_baseurl() . '/images/friendica-64.jpg';
544
545                                 $msg = trim(strip_tags(bbcode($msg)));*/
546
547                                 // New code
548
549                                 // Looking for the first image
550                                 $image = '';
551                                 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
552                                         $image = $matches[3];
553
554                                 if ($image == '')
555                                         if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
556                                                 $image = $matches[1];
557
558                                 // When saved into the database the content is sent through htmlspecialchars
559                                 // That means that we have to decode all image-urls
560                                 $image = htmlspecialchars_decode($image);
561
562                                 // Checking for a bookmark element
563                                 $body = $b['body'];
564                                 if (strpos($body, "[bookmark") !== false) {
565                                         // splitting the text in two parts:
566                                         // before and after the bookmark
567                                         $pos = strpos($body, "[bookmark");
568                                         $body1 = substr($body, 0, $pos);
569                                         $body2 = substr($body, $pos);
570
571                                         // Removing the bookmark and all quotes after the bookmark
572                                         // they are mostly only the content after the bookmark.
573                                         $body2 = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'',$body2);
574                                         $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
575                                         $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
576
577                                         $body = $body1.$body2;
578                                 }
579
580                                 // Convert recycle signs
581                                 $body = str_replace("\t", " ", $body);
582                                 // recycle 1
583                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
584                                 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
585                                 // recycle 2 (Test)
586                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
587                                 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
588
589                                 // share element
590                                 $body = preg_replace_callback("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]/ism","fbpost_ShareAttributes", $body);
591
592                                 $bodyparts = explode("\t", $body);
593                                 // Doesn't help with multiple repeats - the problem has to be solved later
594                                 if (sizeof($bodyparts) == 3) {
595                                         $html = bbcode($bodyparts[2], false, false);
596                                         $test = trim(html2plain($html, 0, true));
597
598                                         if (trim($bodyparts[0]) == "")
599                                                 $body = trim($bodyparts[2]);
600                                         else if (trim($test) == "")
601                                                 $body = trim($bodyparts[0]);
602                                         else
603                                                 $body = trim($bodyparts[0])."\n\n".trim($bodyparts[1])."[quote]".trim($bodyparts[2])."[/quote]";
604                                 } else
605                                         $body = str_replace("\t", "", $body);
606
607                                 // At first convert the text to html
608                                 $html = bbcode($body, false, false);
609
610                                 // Then convert it to plain text
611                                 $msg = trim($b['title']." \n\n".html2plain($html, 0, true));
612
613                                 // Removing useless spaces
614                                 if (substr($msg, -2) == "«")
615                                         $msg = trim(substr($msg, 0, -2))."«";
616
617                                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
618
619                                 // Removing multiple newlines
620                                 while (strpos($msg, "\n\n\n") !== false)
621                                         $msg = str_replace("\n\n\n", "\n\n", $msg);
622
623                                 // add any attachments as text urls
624                                 $arr = explode(',',$b['attach']);
625
626                                 if(count($arr)) {
627                                         $msg .= "\n";
628                                         foreach($arr as $r) {
629                                                 $matches = false;
630                                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
631                                                 if($cnt) {
632                                                         $msg .= "\n".$matches[1];
633                                                 }
634                                         }
635                                 }
636
637                                 $link = '';
638                                 $linkname = '';
639                                 // look for bookmark-bbcode and handle it with priority
640                                 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
641                                         $link = $matches[1];
642                                         $linkname = $matches[2];
643                                 }
644
645                                 // If there is no bookmark element then take the first link
646                                 if ($link == '') {
647                                         $links = collecturls($html);
648                                         if (sizeof($links) > 0) {
649                                                 reset($links);
650                                                 $link = current($links);
651                                         }
652                                 }
653
654                                 // Remove trailing and leading spaces
655                                 $msg = trim($msg);
656
657
658                                 // Fallback - if message is empty
659                                 if(!strlen($msg))
660                                         $msg = $linkname;
661
662                                 if(!strlen($msg))
663                                         $msg = $link;
664
665                                 if(!strlen($msg))
666                                         $msg = $image;
667
668                                 // If there is nothing to post then exit
669                                 if(!strlen($msg))
670                                         return;
671
672                                 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
673
674                                 $video = "";
675
676                                 if($likes) {
677                                         $postvars = array('access_token' => $fb_token);
678                                 } else {
679                                         // message, picture, link, name, caption, description, source, place, tags
680                                         if(trim($link) != "")
681                                                 if (@exif_imagetype($link) != 0) {
682                                                         $image = $link;
683                                                         $link = "";
684                                                 }
685
686                                         $postvars = array(
687                                                 'access_token' => $fb_token,
688                                                 'message' => $msg
689                                         );
690                                         if(trim($image) != "")
691                                                 $postvars['picture'] = $image;
692
693                                         if(trim($link) != "") {
694                                                 $postvars['link'] = $link;
695
696                                                 if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
697                                                         $video = $link;
698                                                 }
699                                         }
700                                         if(trim($linkname) != "")
701                                                 $postvars['name'] = $linkname;
702                                 }
703
704                                 if(($b['private']) && ($toplevel)) {
705                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
706                                         if(count($allow_arr))
707                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
708                                         if(count($deny_arr))
709                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
710                                         $postvars['privacy'] .= '}';
711
712                                 }
713
714                                 $post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
715                                 $page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
716                                 if ((intval($post_to_page) != 0) and ($page_access_token != ""))
717                                         $target = $post_to_page;
718                                 else
719                                         $target = "me";
720
721                                 if($reply) {
722                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
723                                 } else if (($video != "") or (($image == "") and ($link != ""))) {
724                                         // If it is a link to a video or a link without a preview picture then post it as a link
725                                         if ($video != "")
726                                                 $link = $video;
727
728                                         $postvars = array(
729                                                 'access_token' => $fb_token,
730                                                 'link' => $link,
731                                         );
732                                         if ($msg != $video)
733                                                 $postvars['message'] = $msg;
734
735                                         $url = 'https://graph.facebook.com/'.$target.'/links';
736                                 } else if (($link == "") and ($image != "")) {
737                                         // If it is only an image without a page link then post this image as a photo
738                                         $postvars = array(
739                                                 'access_token' => $fb_token,
740                                                 'url' => $image,
741                                         );
742                                         if ($msg != $image)
743                                                 $postvars['message'] = $msg;
744
745                                         $url = 'https://graph.facebook.com/'.$target.'/photos';
746                                 } else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
747                                         $url = 'https://graph.facebook.com/'.$target.'/feed';
748                                         if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
749                                                 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' .  $b['plink'] . '"}';
750                                 } else {
751                                         // if its only a message and a subject and the message is larger than 500 characters then post it as note
752                                         $postvars = array(
753                                                 'access_token' => $fb_token,
754                                                 'message' => bbcode($b['body'], false, false),
755                                                 'subject' => $b['title'],
756                                         );
757                                         $url = 'https://graph.facebook.com/'.$target.'/notes';
758                                 }
759
760                                 // Post to page?
761                                 if (!$reply and ($target != "me") and $page_access_token)
762                                         $postvars['access_token'] = $page_access_token;
763
764                                 logger('facebook: post to ' . $url);
765                                 logger('facebook: postvars: ' . print_r($postvars,true));
766
767                                 // "test_mode" prevents anything from actually being posted.
768                                 // Otherwise, let's do it.
769
770                                 if(! get_config('facebook','test_mode')) {
771                                         $x = post_url($url, $postvars);
772                                         logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
773
774                                         $retj = json_decode($x);
775                                         if($retj->id) {
776                                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
777                                                         dbesc('fb::' . $retj->id),
778                                                         intval($b['id'])
779                                                 );
780                                         }
781                                         else {
782                                                 if(! $likes) {
783                                                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
784                                                         require_once('include/queue_fn.php');
785                                                         add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
786                                                         notice( t('Facebook post failed. Queued for retry.') . EOL);
787                                                 }
788
789                                                 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
790                                                         logger('Facebook session has expired due to changed password.', LOGGER_DEBUG);
791
792                                                         $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
793                                                         if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
794                                                                 require_once('include/enotify.php');
795
796                                                                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']) );
797                                                                 notification(array(
798                                                                         'uid' => $b['uid'],
799                                                                         'type' => NOTIFY_SYSTEM,
800                                                                         'system_type' => 'facebook_connection_invalid',
801                                                                         'language'     => $r[0]['language'],
802                                                                         'to_name'      => $r[0]['username'],
803                                                                         'to_email'     => $r[0]['email'],
804                                                                         'source_name'  => t('Administrator'),
805                                                                         'source_link'  => $a->config["system"]["url"],
806                                                                         'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
807                                                                 ));
808
809                                                                 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
810                                                         } else logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
811                                                 }
812                                         }
813                                 }
814                         }
815                 }
816         }
817 }
818
819 /**
820  * @param App $app
821  * @param object $data
822  */
823 function fbpost_enotify(&$app, &$data) {
824         if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
825                 $data['itemlink'] = '/facebook';
826                 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
827                 $data['subject'] = t('Facebook connection became invalid');
828                 $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]");
829         }
830 }
831
832 /**
833  * @param App $a
834  * @param object $b
835  */
836 function fbpost_post_local(&$a,&$b) {
837
838         // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
839         // where we will discover it during background delivery.
840
841         // This can only be triggered by a local user posting to their own wall.
842
843         if((local_user()) && (local_user() == $b['uid'])) {
844
845                 $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
846                 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
847
848                 // if API is used, default to the chosen settings
849                 // but allow a specific override
850
851                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
852                         if(! x($_REQUEST,'facebook_enable'))
853                                 $fb_enable = 1;
854                 }
855
856                 if(! $fb_enable)
857                         return;
858
859                 if(strlen($b['postopts']))
860                         $b['postopts'] .= ',';
861                 $b['postopts'] .= 'facebook';
862         }
863 }
864
865
866 /**
867  * @param App $a
868  * @param object $b
869  */
870 function fbpost_queue_hook(&$a,&$b) {
871
872         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
873                 dbesc(NETWORK_FACEBOOK)
874         );
875         if(! count($qi))
876                 return;
877
878         require_once('include/queue_fn.php');
879
880         foreach($qi as $x) {
881                 if($x['network'] !== NETWORK_FACEBOOK)
882                         continue;
883
884                 logger('facebook_queue: run');
885
886                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
887                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
888                         intval($x['cid'])
889                 );
890                 if(! count($r))
891                         continue;
892
893                 $user = $r[0];
894
895                 $appid  = get_config('facebook', 'appid'  );
896                 $secret = get_config('facebook', 'appsecret' );
897
898                 if($appid && $secret) {
899                         $fb_post   = intval(get_pconfig($user['uid'],'facebook','post'));
900                         $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
901
902                         if($fb_post && $fb_token) {
903                                 logger('facebook_queue: able to post');
904                                 require_once('library/facebook.php');
905
906                                 $z = unserialize($x['content']);
907                                 $item = $z['item'];
908                                 $j = post_url($z['url'],$z['post']);
909
910                                 $retj = json_decode($j);
911                                 if($retj->id) {
912                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
913                                                 dbesc('fb::' . $retj->id),
914                                                 intval($item)
915                                         );
916                                         logger('facebook_queue: success: ' . $j); 
917                                         remove_queue_item($x['id']);
918                                 }
919                                 else {
920                                         logger('facebook_queue: failed: ' . $j);
921                                         update_queue_time($x['id']);
922                                 }
923                         }
924                 }
925         }
926 }
927
928
929 /**
930  * @return bool|string
931  */
932 function fbpost_get_app_access_token() {
933         
934         $acc_token = get_config('facebook','app_access_token');
935         
936         if ($acc_token !== false) return $acc_token;
937         
938         $appid = get_config('facebook','appid');
939         $appsecret = get_config('facebook', 'appsecret');
940         
941         if ($appid === false || $appsecret === false) {
942                 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
943                 return false;
944         }
945         logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
946         $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
947         
948         if(strpos($x,'access_token=') !== false) {
949                 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
950         
951                 $token = str_replace('access_token=', '', $x);
952                 if(strpos($token,'&') !== false)
953                         $token = substr($token,0,strpos($token,'&'));
954                 
955                 if ($token == "") {
956                         logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
957                         return false;
958                 }
959                 set_config('facebook','app_access_token',$token);
960                 return $token;
961         } else {
962                 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
963                 return false;
964         }
965 }
966