]> git.mxchange.org Git - friendica.git/blob - addon/facebook/facebook.php
missed pulling FB comment timestamp, defaulted to now
[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 your site url + '/facebook' (e.g. http://example.com/facebook)
28  *    and click 'Install Facebook posting'.
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);
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                                         continue;
145                                 }
146                                 else {
147
148                                         // create contact record 
149                                         $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `addr`, `alias`, `notify`, `poll`, 
150                                                 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
151                                                 `writable`, `blocked`, `readonly`, `pending` )
152                                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
153                                                 intval($uid),
154                                                 dbesc(datetime_convert()),
155                                                 dbesc($jp->link),
156                                                 dbesc(''),
157                                                 dbesc(''),
158                                                 dbesc($jp->id),
159                                                 dbesc('facebook ' . $jp->id),
160                                                 dbesc($jp->name),
161                                                 dbesc(($jp->nickname) ? $jp->nickname : strtolower($jp->first_name)),
162                                                 dbesc('https://graph.facebook.com/' . $jp->id . '/picture'),
163                                                 dbesc(NETWORK_FACEBOOK),
164                                                 intval(REL_BUD),
165                                                 intval(1),
166                                                 intval(1)
167                                         );
168                                 }
169
170                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
171                                         dbesc($jp->link),
172                                         intval($uid)
173                                 );
174
175                                 if(! count($r)) {
176                                         continue;
177                                 }
178
179                                 $contact = $r[0];
180                                 $contact_id  = $r[0]['id'];
181
182                                 require_once("Photo.php");
183
184                                 $photos = import_profile_photo($r[0]['photo'],$uid,$contact_id);
185
186                                 $r = q("UPDATE `contact` SET `photo` = '%s', 
187                                         `thumb` = '%s',
188                                         `micro` = '%s', 
189                                         `name-date` = '%s', 
190                                         `uri-date` = '%s', 
191                                         `avatar-date` = '%s'
192                                         WHERE `id` = %d LIMIT 1
193                                 ",
194                                         dbesc($photos[0]),
195                                         dbesc($photos[1]),
196                                         dbesc($photos[2]),
197                                         dbesc(datetime_convert()),
198                                         dbesc(datetime_convert()),
199                                         dbesc(datetime_convert()),
200                                         intval($contact_id)
201                                 );                      
202
203                         }
204                 }
205         }
206 }
207
208
209 function facebook_post(&$a) {
210
211         if(local_user()){
212                 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
213                 set_pconfig(local_user(),'facebook','post_by_default', $value);
214         } 
215         return;         
216 }
217
218 function facebook_content(&$a) {
219
220         if(! local_user()) {
221                 notice( t('Permission denied.') . EOL);
222                 return '';
223         }
224
225         if($a->argc > 1 && $a->argv[1] === 'remove') {
226                 del_pconfig(local_user(),'facebook','post');
227                 notice( t('Facebook disabled') . EOL);
228         }
229
230         $fb_installed = get_pconfig(local_user(),'facebook','post');
231
232         $appid = get_config('facebook','appid');
233
234         if(! $appid) {
235                 notice( t('Facebook API key is missing.') . EOL);
236                 return '';
237         }
238
239         $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' 
240                 . $a->get_baseurl() . '/addon/facebook/facebook.css' . '" media="all" />' . "\r\n";
241
242         $o .= '<h3>' . t('Facebook Connect') . '</h3>';
243
244         if(! $fb_installed) { 
245                 $o .= '<div id="facebook-enable-wrapper">';
246
247                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
248                         . $a->get_baseurl() . '/facebook/' . $a->user['nickname'] . '&scope=publish_stream,read_stream,offline_access">' . t('Install Facebook post connector') . '</a>';
249                 $o .= '</div>';
250         }
251
252         if($fb_installed) {
253                 $o .= '<div id="facebook-disable-wrapper">';
254
255                 $o .= '<a href="' . $a->get_baseurl() . '/facebook/remove' . '">' . t('Remove Facebook post connector') . '</a></div>';
256         
257                 $o .= '<div id="facebook-post-default-form">';
258                 $o .= '<form action="facebook" method="post" >';
259                 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
260                 $checked = (($post_by_default) ? ' checked="checked" ' : '');
261                 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . '<br />';
262                 $o .= '<input type="submit" name="submit" value="' . t('Submit') . '" /></form></div>';
263         }
264
265         return $o;
266 }
267
268 function facebook_install() {
269         register_hook('post_local_end',  'addon/facebook/facebook.php', 'facebook_post_hook');
270         register_hook('jot_networks',    'addon/facebook/facebook.php', 'facebook_jot_nets');
271         register_hook('plugin_settings', 'addon/facebook/facebook.php', 'facebook_plugin_settings');
272         register_hook('cron',            'addon/facebook/facebook.php', 'facebook_cron');
273 }
274
275
276 function facebook_uninstall() {
277         unregister_hook('post_local_end',  'addon/facebook/facebook.php', 'facebook_post_hook');
278         unregister_hook('jot_networks',    'addon/facebook/facebook.php', 'facebook_jot_nets');
279         unregister_hook('plugin_settings', 'addon/facebook/facebook.php', 'facebook_plugin_settings');
280         unregister_hook('cron',            'addon/facebook/facebook.php', 'facebook_cron');
281 }
282
283
284 function facebook_cron($a,$b) {
285
286         $last = get_config('facebook','last_poll');
287         
288         if($last) {
289                 $next = $last + 3600;
290                 if($next > time()) 
291                         return;
292         }
293
294         logger('facebook_cron');
295
296         set_config('facebook','last_poll', time());
297
298         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'post' AND `v` = '1' ");
299         if(count($r)) {
300                 foreach($r as $rr) {
301                         // check for new friends once a day
302                         $last_friend_check = get_pconfig($uid,'facebook','friend_check');
303                         if($last_friend_check) 
304                                 $next_friend_check = $last_friend_check + 86400;
305                         if($next_friend_check <= time()) {
306                                 fb_get_friends($uid);
307                                 set_pconfig($uid,'facebook','friend_check',time());
308                         }
309                         fb_consume_all($rr['uid']);
310                 }
311         }       
312 }
313
314
315
316 function facebook_plugin_settings(&$a,&$b) {
317
318         $b .= '<div class="settings-block">';
319         $b .= '<h3>' . t('Facebook') . '</h3>';
320         $b .= '<a href="facebook">' . t('Facebook Connector Settings') . '</a><br />';
321         $b .= '</div>';
322
323 }
324
325 function facebook_jot_nets(&$a,&$b) {
326         if(! local_user())
327                 return;
328
329         $fb_post = get_pconfig(local_user(),'facebook','post');
330         if(intval($fb_post) == 1) {
331                 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
332                 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
333                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . 'value="1" /> ' 
334                         . t('Post to Facebook') . '</div>';     
335         }
336 }
337
338
339 function facebook_post_hook(&$a,&$b) {
340
341         /**
342          * Post to Facebook stream
343          */
344
345         require_once('include/group.php');
346
347         logger('Facebook post');
348
349         $reply = false;
350         $likes = false;
351
352         if((local_user()) && (local_user() == $b['uid'])) {
353
354                 if($b['parent']) {
355                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
356                                 intval($b['parent']),
357                                 intval(local_user())
358                         );
359                         if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
360                                 $reply = substr($r[0]['uri'],4);
361                         else
362                                 return;
363                         logger('facebook reply id=' . $reply);
364                 }
365
366                 if($b['private'] && $reply == false) {
367                         $allow_people = expand_acl($b['allow_cid']);
368                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
369                         $deny_people  = expand_acl($b['deny_cid']);
370                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
371
372                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
373                         $deny = array_unique(array_merge($deny_people,$deny_groups));
374
375                         $allow_str = dbesc(implode(', ',$recipients));
376                         $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'"); 
377                         $allow_arr = array();
378                         if(count($r)) 
379                                 foreach($r as $rr)
380                                         $allow_arr[] = $rr['notify'];
381
382                         $deny_str = dbesc(implode(', ',$deny));
383                         $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'"); 
384                         $deny_arr = array();
385                         if(count($r)) 
386                                 foreach($r as $rr)
387                                         $deny_arr[] = $rr['notify'];
388                         if((! count($allow_arr)) && (! count($deny_arr)))
389                                 return;
390                 }
391
392                 if($b['verb'] == ACTIVITY_LIKE)
393                         $likes = true;                          
394
395
396                 $appid  = get_config('facebook', 'appid'  );
397                 $secret = get_config('facebook', 'appsecret' );
398
399                 if($appid && $secret) {
400
401                         logger('facebook: have appid+secret');
402
403                         $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
404                         $fb_enable = (($fb_post && x($_POST,'facebook_enable')) ? intval($_POST['facebook_enable']) : 0);
405                         $fb_token  = get_pconfig(local_user(),'facebook','access_token');
406
407                         logger('facebook: $fb_post: ' . $fb_post . ' $fb_enable: ' . $fb_enable . ' $fb_token: ' . $fb_token,LOGGER_DEBUG); 
408
409                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box, 
410                         // or it's a private message with facebook participants
411                         // or it's a reply or likes action to an existing facebook post                 
412
413                         if($fb_post && $fb_token && ($fb_enable || $b['private'] || $reply)) {
414                                 logger('facebook: able to post');
415                                 require_once('library/facebook.php');
416                                 require_once('include/bbcode.php');     
417
418                                 $msg = $b['body'];
419
420                                 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
421
422                                 // make links readable before we strip the code
423
424                                 $msg = preg_replace("/\[url=(.+?)\](.+?)\[\/url\]/is",'$2 $1',$msg);
425
426                                 $msg = preg_replace("/\[img\](.+?)\[\/img\]/is", t('Image: ') . '$1',$msg);
427
428                                 $msg = trim(strip_tags(bbcode($msg)));
429                                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
430
431                                 if (strlen($msg) > FACEBOOK_MAXPOSTLEN) {
432                                         $shortlink = "";
433                                         require_once('library/slinky.php');
434
435                                         $display_url = $a->get_baseurl() . '/display/' . $a->user['nickname'] . '/' . $b['id'];
436                                         $slinky = new Slinky( $display_url );
437                                         // setup a cascade of shortening services
438                                         // try to get a short link from these services
439                                         // in the order ur1.ca, trim, id.gd, tinyurl
440                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
441                                         $shortlink = $slinky->short();
442                                         // the new message will be shortened such that "... $shortlink"
443                                         // will fit into the character limit
444                                         $msg = substr($msg, 0, FACEBOOK_MAXPOSTLEN - strlen($shortlink) - 4);
445                                         $msg .= '... ' . $shortlink;
446                                 }
447                                 if(! strlen($msg))
448                                         return;
449
450                                 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
451
452                                 if($likes) { 
453                                         $postvars = array('access_token' => $fb_token);
454                                 }
455                                 else {
456                                         $postvars = array(
457                                                 'access_token' => $fb_token, 
458                                                 'message' => $msg
459                                         );
460                                 }
461
462                                 if(($b['private']) && (! $b['parent'])) {
463                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
464                                         if(count($allow_arr))
465                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
466                                         if(count($deny_arr))
467                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
468                                         $postvars['privacy'] .= '}';
469
470                                 }
471
472                                 if(! $reply) { 
473                                         if($b['plink'])
474                                                 $postvars['actions'] = '{"name": "' . t('View on Friendika') . '", "link": "' .  $b['plink'] . '"}';
475                                 }
476
477                                 if($reply) {
478                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
479                                 }
480                                 else { 
481                                         $url = 'https://graph.facebook.com/me/feed';
482                                 }
483                                 logger('facebook: post to ' . $url);
484                                 logger('facebook: postvars: ' . print_r($postvars,true));
485
486                                 $x = post_url($url, $postvars);
487                                 
488                                 logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
489
490                         }
491                 }
492         }
493 }
494
495
496 function fb_consume_all($uid) {
497
498         require_once('include/items.php');
499
500         $access_token = get_pconfig($uid,'facebook','access_token');
501         if(! $access_token)
502                 return;
503         $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
504         if($s) {
505                 $j = json_decode($s);
506                 logger('fb_consume_stream: wall: ' . print_r($j,true), LOGGER_DATA);
507                 fb_consume_stream($uid,$j,true);
508         }
509         $s = fetch_url('https://graph.facebook.com/me/home?access_token=' . $access_token);
510         if($s) {
511                 $j = json_decode($s);
512                 logger('fb_consume_stream: feed: ' . print_r($j,true), LOGGER_DATA);
513                 fb_consume_stream($uid,$j,false);
514         }
515
516 }
517
518 function fb_consume_stream($uid,$j,$wall = false) {
519         $a = get_app();
520
521         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
522                 intval($uid)
523         );
524
525         $user = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
526                 intval($uid)
527         );
528         if(count($user))
529                 $my_local_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
530
531
532         $self_id = get_pconfig($uid,'facebook','self_id');
533         if(! count($j->data) || (! strlen($self_id)))
534                 return;
535
536         foreach($j->data as $entry) {
537                 logger('fb_consume: entry: ' . print_r($entry,true), LOGGER_DATA);
538                 $datarray = array();
539                 $we_posted = false;
540                 $app = $entry->application;
541                 if($app->id == get_config('facebook','appid') && $wall)
542                         $we_posted = true;
543
544                 if($we_posted) {
545                         $r = q("SELECT * FROM `item` WHERE `wall` = 1 AND `uid` = %d AND `created` > '%s' AND `created` < '%s' AND `deleted` = 0 LIMIT 1",
546                                 intval($uid),
547                                 dbesc(datetime_convert('UTC','UTC',$entry->created_time . ' - 1 minute')),
548                                 dbesc(datetime_convert('UTC','UTC',$entry->created_time . ' + 1 minute'))
549                         );
550                 }
551                 else {
552                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `deleted` = 0 LIMIT 1",
553                                 dbesc('fb::' . $entry->id),
554                                 intval($uid)
555                         );
556                 }
557                 if(count($r)) {
558                         $post_exists = true;
559                         $orig_post = $r[0];
560                         $top_item = $r[0]['id'];
561                 }
562                 else {
563                         $post_exists = false;
564                         $orig_post = null;
565                 }
566
567                 if(! $orig_post) {
568                         $datarray['gravity'] = 0;
569                         $datarray['uid'] = $uid;
570                         $datarray['wall'] = (($wall) ? 1 : 0);
571                         $datarray['uri'] = $datarray['parent-uri'] = 'fb::' . $entry->id;
572                         $from = $entry->from;
573                         if($from->id == $self_id)
574                                 $datarray['contact-id'] = $self[0]['id'];
575                         else {
576                                 $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
577                                         dbesc($from->id),
578                                         intval($uid)
579                                 );
580                                 if(count($r))
581                                         $datarray['contact-id'] = $r[0]['id'];
582                         }
583                         $datarray['verb'] = ACTIVITY_POST;                                              
584                         if($wall) {
585                                 $datarray['owner-name'] = $self[0]['name'];
586                                 $datarray['author-link'] = $self[0]['url'];
587                                 $datarray['author-avatar'] = $self[0]['thumb'];
588                         }
589                         $datarray['author-name'] = $from->name;
590                         $datarray['author-link'] = 'http://facebook.com/profile.php?id=' . $from->id;
591                         $datarray['author-avatar'] = 'https://graph.facebook.com/' . $from->id . '/picture';
592                         $datarray['body'] = $entry->message;
593                         if($entry->picture)
594                                 $datarray['body'] .= "\n\n" . '[img]' . $entry->picture . '[/img]';
595                         if($entry->link)
596                                 $datarray['body'] .= "\n" . linkify($entry->link);
597                         if($entry->name)
598                                 $datarray['body'] .= "\n" . $entry->name;
599                         if($entry->caption)
600                                 $datarray['body'] .= "\n" . $entry->caption;
601                         if($entry->description)
602                                 $datarray['body'] .= "\n" . $entry->description;
603                         $datarray['created'] = datetime_convert('UTC','UTC',$entry->created_time);
604                         $datarray['edited'] = datetime_convert('UTC','UTC',$entry->updated_time);
605                         if($entry->privacy && $entry->privacy->value !== 'EVERYONE')
606                                 $datarray['private'] = 1;                       
607                         $top_item = item_store($datarray);
608                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
609                                 intval($top_item),
610                                 intval($uid)
611                         );                      
612                         if(count($r))
613                                 $orig_post = $r[0];
614
615                 }
616                 $likers = $entry->likes->data;
617                 $comments = $entry->comments->data;
618
619                 if(is_array($likers)) {
620                         foreach($likers as $likes) {
621
622                                 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s' AND `author-link` = '%s'
623                                         LIMIT 1",
624                                         dbesc('fb::' . $entry->id),
625                                         intval($uid),
626                                         dbesc(ACTIVITY_LIKE),
627                                         dbesc('http://facebook.com/profile.php?id=' . $likes->id)
628                                 );
629                                 if(count($r))
630                                         continue;
631                                         
632                                 $likedata = array();
633                                 $likedata['parent'] = $top_item;
634                                 $likedata['verb'] = ACTIVITY_LIKE;
635
636
637                                 $likedata['gravity'] = 3;
638                                 $likedata['uid'] = $uid;
639                                 $likedata['wall'] = (($wall) ? 1 : 0);
640                                 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
641                                 $likedata['parent-uri'] = 'fb::' . $entry->id;
642                                 if($likes->id == $self_id)
643                                         $likedata['contact-id'] = $self[0]['id'];
644                                 else {
645                                         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
646                                                 dbesc($likes->id),
647                                                 intval($uid)
648                                         );
649                                         if(count($r))
650                                                 $likedata['contact-id'] = $r[0]['id'];
651                                 }
652                                 if(! x($likedata,'contact-id'))
653                                         $likedata['contact-id'] = $orig_post['contact-id'];
654
655                                 $likedata['verb'] = ACTIVITY_LIKE;                                              
656                                 $likedata['author-name'] = $likes->name;
657                                 $likedata['author-link'] = 'http://facebook.com/profile.php?id=' . $likes->id;
658                                 $likedata['author-avatar'] = 'https://graph.facebook.com/' . $likes->id . '/picture';
659                                 
660                                 $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
661                                 $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
662                                 $post_type = t('status');
663                         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
664                                 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
665
666                                 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
667                                 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' . 
668                                         '<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>';  
669
670                                 $item = item_store($likedata);                  
671                         }
672                 }
673                 if(is_array($comments)) {
674                         foreach($comments as $cmnt) {
675
676                                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
677                                         intval($uid),
678                                         dbesc('fb::' . $cmnt->id)
679                                 );
680                                 if(count($r))
681                                         continue;
682
683                                 $cmntdata = array();
684                                 $cmntdata['parent'] = $top_item;
685                                 $cmntdata['verb'] = ACTIVITY_POST;
686                                 $cmntdata['gravity'] = 6;
687                                 $cmntdata['uid'] = $uid;
688                                 $cmntdata['wall'] = (($wall) ? 1 : 0);
689                                 $cmntdata['uri'] = 'fb::' . $cmnt->id;
690                                 $cmntdata['parent-uri'] = 'fb::' . $entry->id;
691                                 if($cmnt->from->id == $self_id) {
692                                         $cmntdata['contact-id'] = $self[0]['id'];
693                                         // see if I already posted it here locally and we're now getting it back from FB
694                                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `created` > '%s' AND `created` < '%s' 
695                                                 AND `parent-uri` = '%s' AND `author-link` = '%s' LIMIT 1",
696                                                 intval($uid),
697                                                 dbesc(datetime_convert('UTC','UTC',$cmnt->created_time . ' - 1 minute')),
698                                                 dbesc(datetime_convert('UTC','UTC',$cmnt->created_time . ' + 1 minute')),
699                                                 dbesc('fb::' . $entry->id),
700                                                 dbesc($my_local_url)
701                                         );
702                                         if(count($r))
703                                                 continue;
704                                 }
705                                 elseif(is_array($orig_post) && (x($orig_post,'contact-id')))
706                                         $cmntdata['contact-id'] = $orig_post['contact-id'];
707                                 else {
708                                         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
709                                                 dbesc($cmnt->from->id),
710                                                 intval($uid)
711                                         );
712                                         if(count($r))
713                                                 $cmntdata['contact-id'] = $r[0]['id'];
714                                 }
715                                 $cmntdata['created'] = datetime_convert('UTC','UTC',$cmnt->created_time);
716                                 $cmntdata['edited']  = datetime_convert('UTC','UTC',$cmnt->created_time);
717                                 $cmntdata['verb'] = ACTIVITY_POST;                                              
718                                 $cmntdata['author-name'] = $cmnt->from->name;
719                                 $cmntdata['author-link'] = 'http://facebook.com/profile.php?id=' . $cmnt->from->id;
720                                 $cmntdata['author-avatar'] = 'https://graph.facebook.com/' . $cmnt->from->id . '/picture';
721                                 $cmntdata['body'] = $cmnt->message;
722                                 $item = item_store($cmntdata);                  
723                         }
724
725
726                 }
727
728         }
729
730
731
732
733
734 }