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