]> git.mxchange.org Git - friendica.git/blob - addon/facebook/facebook.php
ae69805fa7dc9306476612fc0f0a2c42769a3d11
[friendica.git] / addon / facebook / facebook.php
1 <?php
2
3 /**
4  * Installing the Friendika/Facebook connector
5  *
6  * 1. register an API key for your site from developer.facebook.com
7  *   a. We'd be very happy if you include "Friendika" in the application name
8  *      to increase name recognition. The Friendika icons are also present
9  *      in the images directory and may be uploaded as a Facebook app icon.
10  *      Use images/friendika-16.jpg for the Icon and images/friendika-128.jpg for the Logo.
11  *   b. The url should be your site URL with a trailing slash.
12  *      You may use http://portal.friendika.com/privacy as the privacy policy
13  *      URL unless your site has different requirements, and 
14  *      http://portal.friendika.com as the Terms of Service URL unless
15  *      you have different requirements. (Friendika is a software application
16  *      and does not require Terms of Service, though your installation of it might).
17  *   c. Set the following values in your .htconfig.php file
18  *         $a->config['facebook']['appid'] = 'xxxxxxxxxxx';
19  *         $a->config['facebook']['appsecret'] = 'xxxxxxxxxxxxxxx';
20  *      Replace with the settings Facebook gives you.
21  * 2. Enable the facebook plugin by including it in .htconfig.php - e.g. 
22  *     $a->config['system']['addon'] = 'plugin1,plugin2,facebook';
23  * 3. Visit the Facebook Settings section of the "Settings->Plugin Settings" page.
24  *    and click 'Install Facebook Connector'.
25  * 4. This will ask you to login to Facebook and grant permission to the 
26  *    plugin to do its stuff. Allow it to do so. 
27  * 5. You're done. To turn it off visit the Plugin Settings page again and
28  *    'Remove Facebook posting'.
29  *
30  * Vidoes and embeds will not be posted if there is no other content. Links 
31  * and images will be converted to a format suitable for the Facebook API and 
32  * long posts truncated - with a link to view the full post. 
33  *
34  * Facebook contacts will not be able to view private photos, as they are not able to
35  * authenticate to your site to establish identity. We will address this 
36  * in a future release.
37  */
38
39 define('FACEBOOK_MAXPOSTLEN', 420);
40
41 /* declare the facebook_module function so that /facebook url requests will land here */
42
43 function facebook_module() {}
44
45
46
47 /* If a->argv[1] is a nickname, this is a callback from Facebook oauth requests. */
48
49 function facebook_init(&$a) {
50
51         if($a->argc != 2)
52                 return;
53         $nick = $a->argv[1];
54         if(strlen($nick))
55                 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
56                                 dbesc($nick)
57                 );
58         if(! count($r))
59                 return;
60
61         $uid           = $r[0]['uid'];
62         $auth_code     = (($_GET['code']) ? $_GET['code'] : '');
63         $error         = (($_GET['error_description']) ? $_GET['error_description'] : '');
64
65
66         if($error)
67                 logger('facebook_init: Error: ' . $error);
68
69         if($auth_code && $uid) {
70
71                 $appid = get_config('facebook','appid');
72                 $appsecret = get_config('facebook', 'appsecret');
73
74                 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
75                         . $appid . '&client_secret=' . $appsecret . '&redirect_uri='
76                         . urlencode($a->get_baseurl() . '/facebook/' . $nick) 
77                         . '&code=' . $auth_code);
78
79                 logger('facebook_init: returned access token: ' . $x, LOGGER_DATA);
80
81                 if(strpos($x,'access_token=') !== false) {
82                         $token = str_replace('access_token=', '', $x);
83                         if(strpos($token,'&') !== false)
84                                 $token = substr($token,0,strpos($token,'&'));
85                         set_pconfig($uid,'facebook','access_token',$token);
86                         set_pconfig($uid,'facebook','post','1');
87                         fb_get_self($uid);
88                         fb_get_friends($uid);
89                         fb_consume_all($uid);
90
91                 }
92
93                 // todo: is this a browser session or a server session? where do we go? 
94         }
95
96 }
97
98
99 function fb_get_self($uid) {
100         $access_token = get_pconfig($uid,'facebook','access_token');
101         if(! $access_token)
102                 return;
103         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
104         if($s) {
105                 $j = json_decode($s);
106                 set_pconfig($uid,'facebook','self_id',(string) $j->id);
107         }
108 }
109
110
111
112 function fb_get_friends($uid) {
113
114         $access_token = get_pconfig($uid,'facebook','access_token');
115
116         $no_linking = get_pconfig($uid,'facebook','no_linking');
117         if($no_linking)
118                 return;
119
120         if(! $access_token)
121                 return;
122         $s = fetch_url('https://graph.facebook.com/me/friends?access_token=' . $access_token);
123         if($s) {
124                 logger('facebook: fb_get_friends: ' . $s, LOGGER_DATA);
125                 $j = json_decode($s);
126                 logger('facebook: fb_get_friends: json: ' . print_r($j,true), LOGGER_DATA);
127                 foreach($j->data as $person) {
128                         $s = fetch_url('https://graph.facebook.com/' . $person->id . '?access_token=' . $access_token);
129                         if($s) {
130                                 $jp = json_decode($s);
131                                 logger('fb_get_friends: info: ' . print_r($jp,true), LOGGER_DATA);
132
133                                 // always use numeric link for consistency
134
135                                 $jp->link = 'http://facebook.com/profile.php?id=' . $person->id;
136
137                                 // check if we already have a contact
138
139                                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
140                                         intval($uid),
141                                         dbesc($jp->link)
142                                 );                      
143
144                                 if(count($r)) {
145
146                                         // check that we have all the photos, this has been known to fail on occasion
147
148                                         if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro'])) {  
149                                                 require_once("Photo.php");
150
151                                                 $photos = import_profile_photo('https://graph.facebook.com/' . $jp->id . '/picture', $uid, $r[0]['id']);
152
153                                                 $r = q("UPDATE `contact` SET `photo` = '%s', 
154                                                         `thumb` = '%s',
155                                                         `micro` = '%s', 
156                                                         `name-date` = '%s', 
157                                                         `uri-date` = '%s', 
158                                                         `avatar-date` = '%s'
159                                                         WHERE `id` = %d LIMIT 1
160                                                 ",
161                                                         dbesc($photos[0]),
162                                                         dbesc($photos[1]),
163                                                         dbesc($photos[2]),
164                                                         dbesc(datetime_convert()),
165                                                         dbesc(datetime_convert()),
166                                                         dbesc(datetime_convert()),
167                                                         intval($r[0]['id'])
168                                                 );                      
169                                         }       
170                                         continue;
171                                 }
172                                 else {
173
174                                         // create contact record 
175                                         $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `addr`, `alias`, `notify`, `poll`, 
176                                                 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
177                                                 `writable`, `blocked`, `readonly`, `pending` )
178                                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
179                                                 intval($uid),
180                                                 dbesc(datetime_convert()),
181                                                 dbesc($jp->link),
182                                                 dbesc(''),
183                                                 dbesc(''),
184                                                 dbesc($jp->id),
185                                                 dbesc('facebook ' . $jp->id),
186                                                 dbesc($jp->name),
187                                                 dbesc(($jp->nickname) ? $jp->nickname : strtolower($jp->first_name)),
188                                                 dbesc('https://graph.facebook.com/' . $jp->id . '/picture'),
189                                                 dbesc(NETWORK_FACEBOOK),
190                                                 intval(REL_BUD),
191                                                 intval(1),
192                                                 intval(1)
193                                         );
194                                 }
195
196                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
197                                         dbesc($jp->link),
198                                         intval($uid)
199                                 );
200
201                                 if(! count($r)) {
202                                         continue;
203                                 }
204
205                                 $contact = $r[0];
206                                 $contact_id  = $r[0]['id'];
207
208                                 require_once("Photo.php");
209
210                                 $photos = import_profile_photo($r[0]['photo'],$uid,$contact_id);
211
212                                 $r = q("UPDATE `contact` SET `photo` = '%s', 
213                                         `thumb` = '%s',
214                                         `micro` = '%s', 
215                                         `name-date` = '%s', 
216                                         `uri-date` = '%s', 
217                                         `avatar-date` = '%s'
218                                         WHERE `id` = %d LIMIT 1
219                                 ",
220                                         dbesc($photos[0]),
221                                         dbesc($photos[1]),
222                                         dbesc($photos[2]),
223                                         dbesc(datetime_convert()),
224                                         dbesc(datetime_convert()),
225                                         dbesc(datetime_convert()),
226                                         intval($contact_id)
227                                 );                      
228
229                         }
230                 }
231         }
232 }
233
234
235 function facebook_post(&$a) {
236
237         $uid = local_user();
238         if($uid){
239
240                 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
241                 set_pconfig($uid,'facebook','post_by_default', $value);
242
243                 $no_linking = get_pconfig($uid,'facebook','no_linking');
244
245                 $linkvalue = ((x($_POST,'facebook_linking')) ? intval($_POST['facebook_linking']) : 0);
246                 set_pconfig($uid,'facebook','no_linking', (($linkvalue) ? 0 : 1));
247
248                 // FB linkage was allowed but has just been turned off - remove all FB contacts and posts
249
250                 if((! intval($no_linking)) && (! intval($linkvalue))) {
251                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' ",
252                                 intval($uid),
253                                 dbesc(NETWORK_FACEBOOK)
254                         );
255                         if(count($r)) {
256                                 require_once('include/Contact.php');
257                                 foreach($r as $rr)
258                                         contact_remove($rr['id']);
259                         }
260                 }
261                 elseif(intval($no_linking) && intval($linkvalue)) {
262                         // FB linkage is now allowed - import stuff.
263                         fb_get_self($uid);
264                         fb_get_friends($uid);
265                         fb_consume_all($uid);
266                 }
267
268                 info( t('Settings updated.') . EOL);
269         } 
270
271         return;         
272 }
273
274 function facebook_content(&$a) {
275
276         if(! local_user()) {
277                 notice( t('Permission denied.') . EOL);
278                 return '';
279         }
280
281         if($a->argc > 1 && $a->argv[1] === 'remove') {
282                 del_pconfig(local_user(),'facebook','post');
283                 info( t('Facebook disabled') . EOL);
284         }
285
286         if($a->argc > 1 && $a->argv[1] === 'friends') {
287                 fb_get_friends(local_user());
288                 info( t('Updating contacts') . EOL);
289         }
290
291
292         $fb_installed = get_pconfig(local_user(),'facebook','post');
293
294         $appid = get_config('facebook','appid');
295
296         if(! $appid) {
297                 notice( t('Facebook API key is missing.') . EOL);
298                 return '';
299         }
300
301         $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' 
302                 . $a->get_baseurl() . '/addon/facebook/facebook.css' . '" media="all" />' . "\r\n";
303
304         $o .= '<h3>' . t('Facebook Connect') . '</h3>';
305
306         if(! $fb_installed) { 
307                 $o .= '<div id="facebook-enable-wrapper">';
308
309                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
310                         . $a->get_baseurl() . '/facebook/' . $a->user['nickname'] . '&scope=publish_stream,read_stream,offline_access">' . t('Install Facebook connector for this account.') . '</a>';
311                 $o .= '</div>';
312         }
313
314         if($fb_installed) {
315                 $o .= '<div id="facebook-disable-wrapper">';
316
317                 $o .= '<a href="' . $a->get_baseurl() . '/facebook/remove' . '">' . t('Remove Facebook connector') . '</a></div>';
318         
319                 $o .= '<div id="facebook-post-default-form">';
320                 $o .= '<form action="facebook" method="post" >';
321                 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
322                 $checked = (($post_by_default) ? ' checked="checked" ' : '');
323                 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . '<br />';
324
325                 $no_linking = get_pconfig(local_user(),'facebook','no_linking');
326                 $checked = (($no_linking) ? '' : ' checked="checked" ');
327                 $o .= '<input type="checkbox" name="facebook_linking" value="1"' . $checked . '/>' . ' ' . t('Link all your Facebook friends and conversations') . '<br />';
328
329
330
331                 $o .= '<input type="submit" name="submit" value="' . t('Submit') . '" /></form></div>';
332         }
333
334         return $o;
335 }
336
337 function facebook_install() {
338         register_hook('post_local_end',   'addon/facebook/facebook.php', 'facebook_post_hook');
339         register_hook('jot_networks',     'addon/facebook/facebook.php', 'facebook_jot_nets');
340         register_hook('plugin_settings',  'addon/facebook/facebook.php', 'facebook_plugin_settings');
341         register_hook('cron',             'addon/facebook/facebook.php', 'facebook_cron');
342         register_hook('queue_predeliver', 'addon/facebook/facebook.php', 'fb_queue_hook');
343 }
344
345
346 function facebook_uninstall() {
347         unregister_hook('post_local_end',   'addon/facebook/facebook.php', 'facebook_post_hook');
348         unregister_hook('jot_networks',     'addon/facebook/facebook.php', 'facebook_jot_nets');
349         unregister_hook('plugin_settings',  'addon/facebook/facebook.php', 'facebook_plugin_settings');
350         unregister_hook('cron',             'addon/facebook/facebook.php', 'facebook_cron');
351         unregister_hook('queue_predeliver', 'addon/facebook/facebook.php', 'fb_queue_hook');
352 }
353
354
355 function facebook_cron($a,$b) {
356
357         $last = get_config('facebook','last_poll');
358         
359         $poll_interval = intval(get_config('facebook','poll_interval'));
360         if(! $poll_interval)
361                 $poll_interval = 3600;
362
363         if($last) {
364                 $next = $last + $poll_interval;
365                 if($next > time()) 
366                         return;
367         }
368
369         logger('facebook_cron');
370
371         set_config('facebook','last_poll', time());
372
373         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'post' AND `v` = '1' ");
374         if(count($r)) {
375                 foreach($r as $rr) {
376                         // check for new friends once a day
377                         $last_friend_check = get_pconfig($rr['uid'],'facebook','friend_check');
378                         if($last_friend_check) 
379                                 $next_friend_check = $last_friend_check + 86400;
380                         if($next_friend_check <= time()) {
381                                 fb_get_friends($rr['uid']);
382                                 set_pconfig($rr['uid'],'facebook','friend_check',time());
383                         }
384                         fb_consume_all($rr['uid']);
385                 }
386         }       
387 }
388
389
390
391 function facebook_plugin_settings(&$a,&$b) {
392
393         $b .= '<div class="settings-block">';
394         $b .= '<h3>' . t('Facebook') . '</h3>';
395         $b .= '<a href="facebook">' . t('Facebook Connector Settings') . '</a><br />';
396         $b .= '</div>';
397
398 }
399
400 function facebook_jot_nets(&$a,&$b) {
401         if(! local_user())
402                 return;
403
404         $fb_post = get_pconfig(local_user(),'facebook','post');
405         if(intval($fb_post) == 1) {
406                 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
407                 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
408                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . 'value="1" /> ' 
409                         . t('Post to Facebook') . '</div>';     
410         }
411 }
412
413
414 function facebook_post_hook(&$a,&$b) {
415
416         /**
417          * Post to Facebook stream
418          */
419
420         require_once('include/group.php');
421
422         logger('Facebook post');
423
424         $reply = false;
425         $likes = false;
426
427         if((local_user()) && (local_user() == $b['uid'])) {
428
429                 if($b['parent']) {
430                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
431                                 intval($b['parent']),
432                                 intval(local_user())
433                         );
434                         if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
435                                 $reply = substr($r[0]['uri'],4);
436                         elseif(count($r) && substr($r[0]['extid'],0,4) === 'fb::')
437                                 $reply = substr($r[0]['extid'],4);
438                         else
439                                 return;
440                         logger('facebook reply id=' . $reply);
441                 }
442
443                 if($b['private'] && $reply === false) {
444                         $allow_people = expand_acl($b['allow_cid']);
445                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
446                         $deny_people  = expand_acl($b['deny_cid']);
447                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
448
449                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
450                         $deny = array_unique(array_merge($deny_people,$deny_groups));
451
452                         $allow_str = dbesc(implode(', ',$recipients));
453                         if($allow_str) {
454                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'"); 
455                                 $allow_arr = array();
456                                 if(count($r)) 
457                                         foreach($r as $rr)
458                                                 $allow_arr[] = $rr['notify'];
459                         }
460
461                         $deny_str = dbesc(implode(', ',$deny));
462                         if($deny_str) {
463                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'"); 
464                                 $deny_arr = array();
465                                 if(count($r)) 
466                                         foreach($r as $rr)
467                                                 $deny_arr[] = $rr['notify'];
468                         }
469
470                         if(count($deny_arr) && (! count($allow_arr))) {
471
472                                 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
473                                 // This might cause the post to be open to public on Facebook, but only to selected members
474                                 // on another network. Since this could potentially leak a post to somebody who was denied, 
475                                 // we will skip posting it to Facebook with a slightly vague but relevant message that will 
476                                 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
477
478                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
479                                 return;
480                         }
481
482
483                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
484
485                         if((! count($allow_arr)) && (! count($deny_arr)))
486                                 return;
487                 }
488
489                 if($b['verb'] == ACTIVITY_LIKE)
490                         $likes = true;                          
491
492
493                 $appid  = get_config('facebook', 'appid'  );
494                 $secret = get_config('facebook', 'appsecret' );
495
496                 if($appid && $secret) {
497
498                         logger('facebook: have appid+secret');
499
500                         $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
501                         $fb_enable = (($fb_post && x($_POST,'facebook_enable')) ? intval($_POST['facebook_enable']) : 0);
502                         $fb_token  = get_pconfig(local_user(),'facebook','access_token');
503
504                         logger('facebook: $fb_post: ' . $fb_post . ' $fb_enable: ' . $fb_enable . ' $fb_token: ' . $fb_token,LOGGER_DEBUG); 
505
506                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box, 
507                         // or it's a private message with facebook participants
508                         // or it's a reply or likes action to an existing facebook post                 
509
510                         if($fb_post && $fb_token && ($fb_enable || $b['private'] || $reply)) {
511                                 logger('facebook: able to post');
512                                 require_once('library/facebook.php');
513                                 require_once('include/bbcode.php');     
514
515                                 $msg = $b['body'];
516
517                                 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
518
519                                 // make links readable before we strip the code
520
521                                 // unless it's a dislike - just send the text as a comment
522
523                                 if($b['verb'] == ACTIVITY_DISLIKE)
524                                         $msg = trim(strip_tags(bbcode($msg)));
525
526                                 $search_str = $a->get_baseurl() . '/search';
527
528                                 if(preg_match("/\[url=(.+?)\](.+?)\[\/url\]/is",$msg,$matches)) {
529
530                                         // don't use hashtags for message link
531
532                                         if(strpos($matches[2],$search_str) === false) {
533                                                 $link = $matches[1];
534                                                 if(substr($matches[2],0,5) != '[img]')
535                                                         $linkname = $matches[2];
536                                         }
537                                 }
538
539                                 $msg = preg_replace("/\[url=(.+?)\](.+?)\[\/url\]/is",'$2 $1',$msg);
540
541                                 if(preg_match("/\[img\](.+?)\[\/img\]/is",$msg,$matches))
542                                         $image = $matches[1];
543
544                                 $msg = preg_replace("/\[img\](.+?)\[\/img\]/is", t('Image: ') . '$1', $msg);
545
546                                 if((strpos($link,$a->get_baseurl()) !== false) && (! $image))
547                                         $image = $a->get_baseurl() . '/images/friendika-64.jpg';
548
549                                 $msg = trim(strip_tags(bbcode($msg)));
550                                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
551
552                                 // add any attachments as text urls
553
554                             $arr = explode(',',$b['attach']);
555
556                             if(count($arr)) {
557                                         $msg .= "\n";
558                                 foreach($arr as $r) {
559                                 $matches = false;
560                                                 $cnt = preg_match('|\[attach\]href=\"(.+?)\" size=\"(.+?)\" type=\"(.+?)\" title=\"(.+?)\"\[\/attach\]|',$r,$matches);
561                                                 if($cnt) {
562                                                         $msg .= $matches[1];
563                                                 }
564                                         }
565                                 }
566
567                                 if (strlen($msg) > FACEBOOK_MAXPOSTLEN) {
568                                         $shortlink = "";
569                                         require_once('library/slinky.php');
570
571                                         $display_url = $a->get_baseurl() . '/display/' . $a->user['nickname'] . '/' . $b['id'];
572                                         $slinky = new Slinky( $display_url );
573                                         // setup a cascade of shortening services
574                                         // try to get a short link from these services
575                                         // in the order ur1.ca, trim, id.gd, tinyurl
576                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
577                                         $shortlink = $slinky->short();
578                                         // the new message will be shortened such that "... $shortlink"
579                                         // will fit into the character limit
580                                         $msg = substr($msg, 0, FACEBOOK_MAXPOSTLEN - strlen($shortlink) - 4);
581                                         $msg .= '... ' . $shortlink;
582                                 }
583                                 if(! strlen($msg))
584                                         return;
585
586                                 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
587
588                                 if($likes) { 
589                                         $postvars = array('access_token' => $fb_token);
590                                 }
591                                 else {
592                                         $postvars = array(
593                                                 'access_token' => $fb_token, 
594                                                 'message' => $msg
595                                         );
596                                         if(isset($image))
597                                                 $postvars['picture'] = $image;
598                                         if(isset($link))
599                                                 $postvars['link'] = $link;
600                                         if(isset($linkname))
601                                                 $postvars['name'] = $linkname;
602                                 }
603
604                                 if(($b['private']) && (! $b['parent'])) {
605                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
606                                         if(count($allow_arr))
607                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
608                                         if(count($deny_arr))
609                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
610                                         $postvars['privacy'] .= '}';
611
612                                 }
613
614                                 if($reply) {
615                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
616                                 }
617                                 else { 
618                                         $url = 'https://graph.facebook.com/me/feed';
619                                         if($b['plink'])
620                                                 $postvars['actions'] = '{"name": "' . t('View on Friendika') . '", "link": "' .  $b['plink'] . '"}';
621                                 }
622
623                                 logger('facebook: post to ' . $url);
624                                 logger('facebook: postvars: ' . print_r($postvars,true));
625
626                                 // "test_mode" prevents anything from actually being posted.
627                                 // Otherwise, let's do it. 
628
629                                 if(! get_config('facebook','test_mode')) {
630                                         $x = post_url($url, $postvars);
631
632                                         $retj = json_decode($x);
633                                         if($retj->id) {
634                                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
635                                                         dbesc('fb::' . $retj->id),
636                                                         intval($b['id'])
637                                                 );
638                                         }
639                                         else {
640                                                 if(! $likes) {
641                                                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
642                                                         q("INSERT INTO `queue` ( `network`, `cid`, `created`, `last`, `content`)
643                                                                 VALUES ( '%s', %d, '%s', '%s', '%s') ",
644                                                                 dbesc(NETWORK_FACEBOOK),
645                                                                 intval($a->contact),
646                                                                 dbesc(datetime_convert()),
647                                                                 dbesc(datetime_convert()),
648                                                                 dbesc($s)
649                                                         );                                                              
650
651                                                         notice( t('Facebook post failed. Queued for retry.') . EOL);
652                                                 }
653                                         }
654                                         
655                                         logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
656                                 }
657                         }
658                 }
659         }
660 }
661
662
663 function fb_queue_hook(&$a,&$b) {
664
665         require_once('include/queue_fn.php');
666         if((! is_array($b)) || (! count($b)))
667                 return;
668         foreach($b as $x) {
669                 if($x['network'] !== NETWORK_FACEBOOK)
670                         continue;
671                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
672                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
673                         intval($x['cid'])
674                 );
675                 if(! count($r))
676                         continue;
677
678                 $user = $r[0];
679
680                 $appid  = get_config('facebook', 'appid'  );
681                 $secret = get_config('facebook', 'appsecret' );
682
683                 if($appid && $secret) {
684                         $fb_post   = intval(get_pconfig($user['uid'],'facebook','post'));
685                         $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
686
687                         if($fb_post && $fb_token) {
688                                 logger('facebook_queue: able to post');
689                                 require_once('library/facebook.php');
690
691                                 $z = unserialize($x['content']);
692                                 $item = $z['item'];
693                                 $j = post_url($z['url'],$z['post']);
694
695                                 $retj = json_decode($j);
696                                 if($retj->id) {
697                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
698                                                 dbesc('fb::' . $retj->id),
699                                                 intval($item)
700                                         );
701                                         logger('facebook queue: success: ' . $j); 
702                                         remove_queue_item($x['id']);
703                                 }
704                                 else {
705                                         logger('facebook_queue: failed: ' . $j);
706                                         update_queue_time($x['id']);
707                                 }
708                         }
709                 }
710         }
711 }
712
713 function fb_consume_all($uid) {
714
715         require_once('include/items.php');
716
717         $access_token = get_pconfig($uid,'facebook','access_token');
718         if(! $access_token)
719                 return;
720         $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
721         if($s) {
722                 $j = json_decode($s);
723                 logger('fb_consume_stream: wall: ' . print_r($j,true), LOGGER_DATA);
724                 fb_consume_stream($uid,$j,true);
725         }
726         $s = fetch_url('https://graph.facebook.com/me/home?access_token=' . $access_token);
727         if($s) {
728                 $j = json_decode($s);
729                 logger('fb_consume_stream: feed: ' . print_r($j,true), LOGGER_DATA);
730                 fb_consume_stream($uid,$j,false);
731         }
732
733 }
734
735 function fb_consume_stream($uid,$j,$wall = false) {
736         $a = get_app();
737
738         $no_linking = get_pconfig($uid,'facebook','no_linking');
739         if($no_linking)
740                 return;
741
742         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
743                 intval($uid)
744         );
745
746         $user = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
747                 intval($uid)
748         );
749         if(count($user))
750                 $my_local_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
751
752
753         $self_id = get_pconfig($uid,'facebook','self_id');
754         if(! count($j->data) || (! strlen($self_id)))
755                 return;
756
757         foreach($j->data as $entry) {
758                 logger('fb_consume: entry: ' . print_r($entry,true), LOGGER_DATA);
759                 $datarray = array();
760
761                 $r = q("SELECT * FROM `item` WHERE ( `uri` = '%s' OR `extid` = '%s') AND `uid` = %d LIMIT 1",
762                                 dbesc('fb::' . $entry->id),
763                                 dbesc('fb::' . $entry->id),
764                                 intval($uid)
765                 );
766                 if(count($r)) {
767                         $post_exists = true;
768                         $orig_post = $r[0];
769                         $top_item = $r[0]['id'];
770                 }
771                 else {
772                         $post_exists = false;
773                         $orig_post = null;
774                 }
775
776                 if(! $orig_post) {
777                         $datarray['gravity'] = 0;
778                         $datarray['uid'] = $uid;
779                         $datarray['wall'] = (($wall) ? 1 : 0);
780                         $datarray['uri'] = $datarray['parent-uri'] = 'fb::' . $entry->id;
781                         $from = $entry->from;
782                         if($from->id == $self_id)
783                                 $datarray['contact-id'] = $self[0]['id'];
784                         else {
785                                 $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
786                                         dbesc($from->id),
787                                         intval($uid)
788                                 );
789                                 if(count($r))
790                                         $datarray['contact-id'] = $r[0]['id'];
791                         }
792
793                         // don't store post if we don't have a contact
794
795                         if(! x($datarray,'contact-id')) {
796                                 logger('no contact: post ignored');
797                                 continue; 
798                         }
799
800                         $datarray['verb'] = ACTIVITY_POST;                                              
801                         if($wall) {
802                                 $datarray['owner-name'] = $self[0]['name'];
803                                 $datarray['owner-link'] = $self[0]['url'];
804                                 $datarray['owner-avatar'] = $self[0]['thumb'];
805                         }
806                         $datarray['author-name'] = $from->name;
807                         $datarray['author-link'] = 'http://facebook.com/profile.php?id=' . $from->id;
808                         $datarray['author-avatar'] = 'https://graph.facebook.com/' . $from->id . '/picture';
809                         $datarray['plink'] = $datarray['author-link'] . '&v=wall&story_fbid=' . substr($entry->id,strpos($entry->id,'_') + 1);
810
811                         $datarray['body'] = $entry->message;
812                         if($entry->picture)
813                                 $datarray['body'] .= "\n\n" . '[img]' . $entry->picture . '[/img]';
814                         if($entry->link)
815                                 $datarray['body'] .= "\n" . linkify($entry->link);
816                         if($entry->name)
817                                 $datarray['body'] .= "\n" . $entry->name;
818                         if($entry->caption)
819                                 $datarray['body'] .= "\n" . $entry->caption;
820                         if($entry->description)
821                                 $datarray['body'] .= "\n" . $entry->description;
822                         $datarray['created'] = datetime_convert('UTC','UTC',$entry->created_time);
823                         $datarray['edited'] = datetime_convert('UTC','UTC',$entry->updated_time);
824                         if($entry->privacy && $entry->privacy->value !== 'EVERYONE')
825                                 $datarray['private'] = 1;                       
826                         $top_item = item_store($datarray);
827                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
828                                 intval($top_item),
829                                 intval($uid)
830                         );                      
831                         if(count($r)) {
832                                 $orig_post = $r[0];
833                                 logger('fb: new top level item posted');
834                         }
835                 }
836
837                 if(isset($entry->likes) && isset($entry->likes->data))
838                         $likers = $entry->likes->data;
839                 else
840                         $likers = null;
841
842                 if(isset($entry->comments) && isset($entry->comments->data))
843                         $comments = $entry->comments->data;
844                 else
845                         $comments = null;
846
847                 if(is_array($likers)) {
848                         foreach($likers as $likes) {
849
850                                 if(! $orig_post)
851                                         continue;
852
853                                 // If we posted the like locally, it will be found with our url, not the FB url.
854
855                                 $second_url = (($likes->id == $self_id) ? $self[0]['url'] : 'http://facebook.com/profile.php?id=' . $likes->id); 
856
857                                 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s' 
858                                         AND ( `author-link` = '%s' OR `author-link` = '%s' ) LIMIT 1",
859                                         dbesc($orig_post['uri']),
860                                         intval($uid),
861                                         dbesc(ACTIVITY_LIKE),
862                                         dbesc('http://facebook.com/profile.php?id=' . $likes->id),
863                                         dbesc($second_url)
864                                 );
865
866                                 if(count($r))
867                                         continue;
868                                         
869                                 $likedata = array();
870                                 $likedata['parent'] = $top_item;
871                                 $likedata['verb'] = ACTIVITY_LIKE;
872                                 $likedata['gravity'] = 3;
873                                 $likedata['uid'] = $uid;
874                                 $likedata['wall'] = (($wall) ? 1 : 0);
875                                 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
876                                 $likedata['parent-uri'] = $orig_post['uri'];
877                                 if($likes->id == $self_id)
878                                         $likedata['contact-id'] = $self[0]['id'];
879                                 else {
880                                         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
881                                                 dbesc($likes->id),
882                                                 intval($uid)
883                                         );
884                                         if(count($r))
885                                                 $likedata['contact-id'] = $r[0]['id'];
886                                 }
887                                 if(! x($likedata,'contact-id'))
888                                         $likedata['contact-id'] = $orig_post['contact-id'];
889
890                                 $likedata['verb'] = ACTIVITY_LIKE;                                              
891                                 $likedata['author-name'] = $likes->name;
892                                 $likedata['author-link'] = 'http://facebook.com/profile.php?id=' . $likes->id;
893                                 $likedata['author-avatar'] = 'https://graph.facebook.com/' . $likes->id . '/picture';
894                                 
895                                 $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
896                                 $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
897                                 $post_type = t('status');
898                         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
899                                 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
900
901                                 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
902                                 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' . 
903                                         '<id>' . $orig_post['uri'] . '</id><link>' . xmlify('<link rel="alternate" type="text/html" href="' . $orig_post['plink'] . '">') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';  
904
905                                 $item = item_store($likedata);                  
906                         }
907                 }
908                 if(is_array($comments)) {
909                         foreach($comments as $cmnt) {
910
911                                 if(! $orig_post)
912                                         continue;
913
914                                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND ( `uri` = '%s' OR `extid` = '%s' ) LIMIT 1",
915                                         intval($uid),
916                                         dbesc('fb::' . $cmnt->id),
917                                         dbesc('fb::' . $cmnt->id)
918                                 );
919                                 if(count($r))
920                                         continue;
921
922                                 $cmntdata = array();
923                                 $cmntdata['parent'] = $top_item;
924                                 $cmntdata['verb'] = ACTIVITY_POST;
925                                 $cmntdata['gravity'] = 6;
926                                 $cmntdata['uid'] = $uid;
927                                 $cmntdata['wall'] = (($wall) ? 1 : 0);
928                                 $cmntdata['uri'] = 'fb::' . $cmnt->id;
929                                 $cmntdata['parent-uri'] = $orig_post['uri'];
930                                 if($cmnt->from->id == $self_id) {
931                                         $cmntdata['contact-id'] = $self[0]['id'];
932                                 }
933                                 else {
934                                         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
935                                                 dbesc($cmnt->from->id),
936                                                 intval($uid)
937                                         );
938                                         if(count($r)) {
939                                                 $cmntdata['contact-id'] = $r[0]['id'];
940                                                 if($r[0]['blocked'] || $r[0]['readonly'])
941                                                         continue;
942                                         }
943                                 }
944                                 if(! x($cmntdata,'contact-id'))
945                                         $cmntdata['contact-id'] = $orig_post['contact-id'];
946
947                                 $cmntdata['created'] = datetime_convert('UTC','UTC',$cmnt->created_time);
948                                 $cmntdata['edited']  = datetime_convert('UTC','UTC',$cmnt->created_time);
949                                 $cmntdata['verb'] = ACTIVITY_POST;                                              
950                                 $cmntdata['author-name'] = $cmnt->from->name;
951                                 $cmntdata['author-link'] = 'http://facebook.com/profile.php?id=' . $cmnt->from->id;
952                                 $cmntdata['author-avatar'] = 'https://graph.facebook.com/' . $cmnt->from->id . '/picture';
953                                 $cmntdata['body'] = $cmnt->message;
954                                 $item = item_store($cmntdata);                  
955                         }
956                 }
957         }
958 }
959