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