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