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