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