]> git.mxchange.org Git - friendica.git/blob - addon/facebook/facebook.php
8999561c85abcaeeca2216a1afaab2d00ece0e4e
[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);
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         if($a->argc > 1 && $a->argv[1] === 'friends') {
231                 fb_get_friends(local_user());
232                 notice( t('Updating contacts') . EOL);
233         }
234
235
236         $fb_installed = get_pconfig(local_user(),'facebook','post');
237
238         $appid = get_config('facebook','appid');
239
240         if(! $appid) {
241                 notice( t('Facebook API key is missing.') . EOL);
242                 return '';
243         }
244
245         $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' 
246                 . $a->get_baseurl() . '/addon/facebook/facebook.css' . '" media="all" />' . "\r\n";
247
248         $o .= '<h3>' . t('Facebook Connect') . '</h3>';
249
250         if(! $fb_installed) { 
251                 $o .= '<div id="facebook-enable-wrapper">';
252
253                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
254                         . $a->get_baseurl() . '/facebook/' . $a->user['nickname'] . '&scope=publish_stream,read_stream,offline_access">' . t('Install Facebook connector for this account.') . '</a>';
255                 $o .= '</div>';
256         }
257
258         if($fb_installed) {
259                 $o .= '<div id="facebook-disable-wrapper">';
260
261                 $o .= '<a href="' . $a->get_baseurl() . '/facebook/remove' . '">' . t('Remove Facebook connector') . '</a></div>';
262         
263                 $o .= '<div id="facebook-post-default-form">';
264                 $o .= '<form action="facebook" method="post" >';
265                 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
266                 $checked = (($post_by_default) ? ' checked="checked" ' : '');
267                 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . '<br />';
268                 $o .= '<input type="submit" name="submit" value="' . t('Submit') . '" /></form></div>';
269         }
270
271         return $o;
272 }
273
274 function facebook_install() {
275         register_hook('post_local_end',  'addon/facebook/facebook.php', 'facebook_post_hook');
276         register_hook('jot_networks',    'addon/facebook/facebook.php', 'facebook_jot_nets');
277         register_hook('plugin_settings', 'addon/facebook/facebook.php', 'facebook_plugin_settings');
278         register_hook('cron',            'addon/facebook/facebook.php', 'facebook_cron');
279 }
280
281
282 function facebook_uninstall() {
283         unregister_hook('post_local_end',  'addon/facebook/facebook.php', 'facebook_post_hook');
284         unregister_hook('jot_networks',    'addon/facebook/facebook.php', 'facebook_jot_nets');
285         unregister_hook('plugin_settings', 'addon/facebook/facebook.php', 'facebook_plugin_settings');
286         unregister_hook('cron',            'addon/facebook/facebook.php', 'facebook_cron');
287 }
288
289
290 function facebook_cron($a,$b) {
291
292         $last = get_config('facebook','last_poll');
293         
294         if($last) {
295                 $next = $last + 3600;
296                 if($next > time()) 
297                         return;
298         }
299
300         logger('facebook_cron');
301
302         set_config('facebook','last_poll', time());
303
304         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'post' AND `v` = '1' ");
305         if(count($r)) {
306                 foreach($r as $rr) {
307                         // check for new friends once a day
308                         $last_friend_check = get_pconfig($rr['uid'],'facebook','friend_check');
309                         if($last_friend_check) 
310                                 $next_friend_check = $last_friend_check + 86400;
311                         if($next_friend_check <= time()) {
312                                 fb_get_friends($rr['uid']);
313                                 set_pconfig($rr['uid'],'facebook','friend_check',time());
314                         }
315                         fb_consume_all($rr['uid']);
316                 }
317         }       
318 }
319
320
321
322 function facebook_plugin_settings(&$a,&$b) {
323
324         $b .= '<div class="settings-block">';
325         $b .= '<h3>' . t('Facebook') . '</h3>';
326         $b .= '<a href="facebook">' . t('Facebook Connector Settings') . '</a><br />';
327         $b .= '</div>';
328
329 }
330
331 function facebook_jot_nets(&$a,&$b) {
332         if(! local_user())
333                 return;
334
335         $fb_post = get_pconfig(local_user(),'facebook','post');
336         if(intval($fb_post) == 1) {
337                 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
338                 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
339                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . 'value="1" /> ' 
340                         . t('Post to Facebook') . '</div>';     
341         }
342 }
343
344
345 function facebook_post_hook(&$a,&$b) {
346
347         /**
348          * Post to Facebook stream
349          */
350
351         require_once('include/group.php');
352
353         logger('Facebook post');
354
355         $reply = false;
356         $likes = false;
357
358         if((local_user()) && (local_user() == $b['uid'])) {
359
360                 if($b['parent']) {
361                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
362                                 intval($b['parent']),
363                                 intval(local_user())
364                         );
365                         if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
366                                 $reply = substr($r[0]['uri'],4);
367                         else
368                                 return;
369                         logger('facebook reply id=' . $reply);
370                 }
371
372                 if($b['private'] && $reply == false) {
373                         $allow_people = expand_acl($b['allow_cid']);
374                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
375                         $deny_people  = expand_acl($b['deny_cid']);
376                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
377
378                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
379                         $deny = array_unique(array_merge($deny_people,$deny_groups));
380
381                         $allow_str = dbesc(implode(', ',$recipients));
382                         if($allow_str) {
383                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'"); 
384                                 $allow_arr = array();
385                                 if(count($r)) 
386                                         foreach($r as $rr)
387                                                 $allow_arr[] = $rr['notify'];
388                         }
389
390                         $deny_str = dbesc(implode(', ',$deny));
391                         if($deny_str) {
392                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'"); 
393                                 $deny_arr = array();
394                                 if(count($r)) 
395                                         foreach($r as $rr)
396                                                 $deny_arr[] = $rr['notify'];
397                         }
398
399                         if(count($deny_arr) && (! count($allow_arr))) {
400
401                                 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
402                                 // This might cause the post to be open to public on Facebook, but only to selected members
403                                 // on another network. Since this could potentially leak a post to somebody who was denied, 
404                                 // we will skip posting it to Facebook with a slightly vague but relevant message that will 
405                                 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
406
407                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
408                                 return;
409                         }
410
411
412                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
413
414                         if((! count($allow_arr)) && (! count($deny_arr)))
415                                 return;
416                 }
417
418                 if($b['verb'] == ACTIVITY_LIKE)
419                         $likes = true;                          
420
421
422                 $appid  = get_config('facebook', 'appid'  );
423                 $secret = get_config('facebook', 'appsecret' );
424
425                 if($appid && $secret) {
426
427                         logger('facebook: have appid+secret');
428
429                         $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
430                         $fb_enable = (($fb_post && x($_POST,'facebook_enable')) ? intval($_POST['facebook_enable']) : 0);
431                         $fb_token  = get_pconfig(local_user(),'facebook','access_token');
432
433                         logger('facebook: $fb_post: ' . $fb_post . ' $fb_enable: ' . $fb_enable . ' $fb_token: ' . $fb_token,LOGGER_DEBUG); 
434
435                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box, 
436                         // or it's a private message with facebook participants
437                         // or it's a reply or likes action to an existing facebook post                 
438
439                         if($fb_post && $fb_token && ($fb_enable || $b['private'] || $reply)) {
440                                 logger('facebook: able to post');
441                                 require_once('library/facebook.php');
442                                 require_once('include/bbcode.php');     
443
444                                 $msg = $b['body'];
445
446                                 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
447
448                                 // make links readable before we strip the code
449
450                                 if(preg_match("/\[url=(.+?)\](.+?)\[\/url\]/is",$msg,$matches)) {
451
452                                         $link = $matches[1];
453                                         if(substr($matches[2],0,5) != '[img]' )
454                                                 $linkname = $matches[2];
455                                 }
456
457                                 $msg = preg_replace("/\[url=(.+?)\](.+?)\[\/url\]/is",'$2 $1',$msg);
458
459                                 if(preg_match("/\[img\](.+?)\[\/img\]/is",$msg,$matches))
460                                         $image = $matches[1];
461
462                                 $msg = preg_replace("/\[img\](.+?)\[\/img\]/is", t('Image: ') . '$1', $msg);
463
464
465
466                                 $msg = trim(strip_tags(bbcode($msg)));
467                                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
468
469                                 if (strlen($msg) > FACEBOOK_MAXPOSTLEN) {
470                                         $shortlink = "";
471                                         require_once('library/slinky.php');
472
473                                         $display_url = $a->get_baseurl() . '/display/' . $a->user['nickname'] . '/' . $b['id'];
474                                         $slinky = new Slinky( $display_url );
475                                         // setup a cascade of shortening services
476                                         // try to get a short link from these services
477                                         // in the order ur1.ca, trim, id.gd, tinyurl
478                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
479                                         $shortlink = $slinky->short();
480                                         // the new message will be shortened such that "... $shortlink"
481                                         // will fit into the character limit
482                                         $msg = substr($msg, 0, FACEBOOK_MAXPOSTLEN - strlen($shortlink) - 4);
483                                         $msg .= '... ' . $shortlink;
484                                 }
485                                 if(! strlen($msg))
486                                         return;
487
488                                 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
489
490                                 if($likes) { 
491                                         $postvars = array('access_token' => $fb_token);
492                                 }
493                                 else {
494                                         $postvars = array(
495                                                 'access_token' => $fb_token, 
496                                                 'message' => $msg
497                                         );
498                                         if(isset($image))
499                                                 $postvars['picture'] = $image;
500                                         if(isset($link))
501                                                 $postvars['link'] = $link;
502                                         if(isset($linkname))
503                                                 $postvars['name'] = $linkname;
504                                 }
505
506                                 if(($b['private']) && (! $b['parent'])) {
507                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
508                                         if(count($allow_arr))
509                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
510                                         if(count($deny_arr))
511                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
512                                         $postvars['privacy'] .= '}';
513
514                                 }
515
516                                 if($reply) {
517                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
518                                 }
519                                 else { 
520                                         $url = 'https://graph.facebook.com/me/feed';
521                                         if($b['plink'])
522                                                 $postvars['actions'] = '{"name": "' . t('View on Friendika') . '", "link": "' .  $b['plink'] . '"}';
523                                 }
524
525                                 logger('facebook: post to ' . $url);
526                                 logger('facebook: postvars: ' . print_r($postvars,true));
527
528                                 // "test_mode" prevents anything from actually being posted.
529                                 // Otherwise, let's do it. 
530
531                                 if(! get_config('facebook','test_mode'))
532                                         $x = post_url($url, $postvars);
533
534                                 $retj = json_decode($x);
535                                 if($retj->id) {
536                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
537                                                 dbesc('fb::' . $retj->id),
538                                                 intval($b['id'])
539                                         );
540                                 }
541                                 
542                                 logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
543
544                         }
545                 }
546         }
547 }
548
549
550 function fb_consume_all($uid) {
551
552         require_once('include/items.php');
553
554         $access_token = get_pconfig($uid,'facebook','access_token');
555         if(! $access_token)
556                 return;
557         $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
558         if($s) {
559                 $j = json_decode($s);
560                 logger('fb_consume_stream: wall: ' . print_r($j,true), LOGGER_DATA);
561                 fb_consume_stream($uid,$j,true);
562         }
563         $s = fetch_url('https://graph.facebook.com/me/home?access_token=' . $access_token);
564         if($s) {
565                 $j = json_decode($s);
566                 logger('fb_consume_stream: feed: ' . print_r($j,true), LOGGER_DATA);
567                 fb_consume_stream($uid,$j,false);
568         }
569
570 }
571
572 function fb_consume_stream($uid,$j,$wall = false) {
573         $a = get_app();
574
575         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
576                 intval($uid)
577         );
578
579         $user = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
580                 intval($uid)
581         );
582         if(count($user))
583                 $my_local_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
584
585
586         $self_id = get_pconfig($uid,'facebook','self_id');
587         if(! count($j->data) || (! strlen($self_id)))
588                 return;
589
590         foreach($j->data as $entry) {
591                 logger('fb_consume: entry: ' . print_r($entry,true), LOGGER_DATA);
592                 $datarray = array();
593                 $we_posted = false;
594                 $app = $entry->application;
595                 if($app->id == get_config('facebook','appid') && $wall)
596                         $we_posted = true;
597
598                 $r = q("SELECT * FROM `item` WHERE ( `uri` = '%s' OR `extid` = '%s') AND `uid` = %d LIMIT 1",
599                                 dbesc('fb::' . $entry->id),
600                                 dbesc('fb::' . $entry->id),
601                                 intval($uid)
602                 );
603                 if(count($r)) {
604                         $post_exists = true;
605                         $orig_post = $r[0];
606                         $top_item = $r[0]['id'];
607                 }
608                 else {
609                         $post_exists = false;
610                         $orig_post = null;
611                 }
612
613                 if(! $orig_post) {
614                         $datarray['gravity'] = 0;
615                         $datarray['uid'] = $uid;
616                         $datarray['wall'] = (($wall) ? 1 : 0);
617                         $datarray['uri'] = $datarray['parent-uri'] = 'fb::' . $entry->id;
618                         $from = $entry->from;
619                         if($from->id == $self_id)
620                                 $datarray['contact-id'] = $self[0]['id'];
621                         else {
622                                 $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
623                                         dbesc($from->id),
624                                         intval($uid)
625                                 );
626                                 if(count($r))
627                                         $datarray['contact-id'] = $r[0]['id'];
628                         }
629
630                         // don't store post if we don't have a contact
631
632                         if(! x($datarray,'contact-id'))
633                                 continue; 
634
635                         $datarray['verb'] = ACTIVITY_POST;                                              
636                         if($wall) {
637                                 $datarray['owner-name'] = $self[0]['name'];
638                                 $datarray['owner-link'] = $self[0]['url'];
639                                 $datarray['owner-avatar'] = $self[0]['thumb'];
640                         }
641                         $datarray['author-name'] = $from->name;
642                         $datarray['author-link'] = 'http://facebook.com/profile.php?id=' . $from->id;
643                         $datarray['author-avatar'] = 'https://graph.facebook.com/' . $from->id . '/picture';
644                         $datarray['plink'] = $datarray['author-link'] . '&v=wall&story_fbid=' . substr($entry->id,strpos($entry->id,'_') + 1);
645
646                         $datarray['body'] = $entry->message;
647                         if($entry->picture)
648                                 $datarray['body'] .= "\n\n" . '[img]' . $entry->picture . '[/img]';
649                         if($entry->link)
650                                 $datarray['body'] .= "\n" . linkify($entry->link);
651                         if($entry->name)
652                                 $datarray['body'] .= "\n" . $entry->name;
653                         if($entry->caption)
654                                 $datarray['body'] .= "\n" . $entry->caption;
655                         if($entry->description)
656                                 $datarray['body'] .= "\n" . $entry->description;
657                         $datarray['created'] = datetime_convert('UTC','UTC',$entry->created_time);
658                         $datarray['edited'] = datetime_convert('UTC','UTC',$entry->updated_time);
659                         if($entry->privacy && $entry->privacy->value !== 'EVERYONE')
660                                 $datarray['private'] = 1;                       
661                         $top_item = item_store($datarray);
662                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
663                                 intval($top_item),
664                                 intval($uid)
665                         );                      
666                         if(count($r))
667                                 $orig_post = $r[0];
668
669                 }
670                 $likers = $entry->likes->data;
671                 $comments = $entry->comments->data;
672
673                 if(is_array($likers)) {
674                         foreach($likers as $likes) {
675
676                                 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s' AND `author-link` = '%s'
677                                         LIMIT 1",
678                                         dbesc('fb::' . $entry->id),
679                                         intval($uid),
680                                         dbesc(ACTIVITY_LIKE),
681                                         dbesc('http://facebook.com/profile.php?id=' . $likes->id)
682                                 );
683                                 if(count($r))
684                                         continue;
685                                         
686                                 $likedata = array();
687                                 $likedata['parent'] = $top_item;
688                                 $likedata['verb'] = ACTIVITY_LIKE;
689
690
691                                 $likedata['gravity'] = 3;
692                                 $likedata['uid'] = $uid;
693                                 $likedata['wall'] = (($wall) ? 1 : 0);
694                                 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
695                                 $likedata['parent-uri'] = 'fb::' . $entry->id;
696                                 if($likes->id == $self_id)
697                                         $likedata['contact-id'] = $self[0]['id'];
698                                 else {
699                                         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
700                                                 dbesc($likes->id),
701                                                 intval($uid)
702                                         );
703                                         if(count($r))
704                                                 $likedata['contact-id'] = $r[0]['id'];
705                                 }
706                                 if(! x($likedata,'contact-id'))
707                                         $likedata['contact-id'] = $orig_post['contact-id'];
708
709                                 $likedata['verb'] = ACTIVITY_LIKE;                                              
710                                 $likedata['author-name'] = $likes->name;
711                                 $likedata['author-link'] = 'http://facebook.com/profile.php?id=' . $likes->id;
712                                 $likedata['author-avatar'] = 'https://graph.facebook.com/' . $likes->id . '/picture';
713                                 
714                                 $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
715                                 $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
716                                 $post_type = t('status');
717                         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
718                                 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
719
720                                 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
721                                 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' . 
722                                         '<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>';  
723
724                                 $item = item_store($likedata);                  
725                         }
726                 }
727                 if(is_array($comments)) {
728                         foreach($comments as $cmnt) {
729
730                                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND ( `uri` = '%s' OR `extid` = '%s' ) LIMIT 1",
731                                         intval($uid),
732                                         dbesc('fb::' . $cmnt->id),
733                                         dbesc('fb::' . $cmnt->id)
734                                 );
735                                 if(count($r))
736                                         continue;
737
738                                 $cmntdata = array();
739                                 $cmntdata['parent'] = $top_item;
740                                 $cmntdata['verb'] = ACTIVITY_POST;
741                                 $cmntdata['gravity'] = 6;
742                                 $cmntdata['uid'] = $uid;
743                                 $cmntdata['wall'] = (($wall) ? 1 : 0);
744                                 $cmntdata['uri'] = 'fb::' . $cmnt->id;
745                                 $cmntdata['parent-uri'] = 'fb::' . $entry->id;
746                                 if($cmnt->from->id == $self_id) {
747                                         $cmntdata['contact-id'] = $self[0]['id'];
748                                 }
749                                 elseif(is_array($orig_post) && (x($orig_post,'contact-id')))
750                                         $cmntdata['contact-id'] = $orig_post['contact-id'];
751                                 else {
752                                         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
753                                                 dbesc($cmnt->from->id),
754                                                 intval($uid)
755                                         );
756                                         if(count($r))
757                                                 $cmntdata['contact-id'] = $r[0]['id'];
758                                 }
759                                 if(! x($cmntdata,'contact-id'))
760                                         return;
761                                 $cmntdata['created'] = datetime_convert('UTC','UTC',$cmnt->created_time);
762                                 $cmntdata['edited']  = datetime_convert('UTC','UTC',$cmnt->created_time);
763                                 $cmntdata['verb'] = ACTIVITY_POST;                                              
764                                 $cmntdata['author-name'] = $cmnt->from->name;
765                                 $cmntdata['author-link'] = 'http://facebook.com/profile.php?id=' . $cmnt->from->id;
766                                 $cmntdata['author-avatar'] = 'https://graph.facebook.com/' . $cmnt->from->id . '/picture';
767                                 $cmntdata['body'] = $cmnt->message;
768                                 $item = item_store($cmntdata);                  
769                         }
770                 }
771         }
772 }
773