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