]> git.mxchange.org Git - friendica-addons.git/blob - facebook/facebook.php
Synchronizing comments and likes of individual FB-comments
[friendica-addons.git] / facebook / facebook.php
1 <?php
2 /**
3  * Name: Facebook Connector
4  * Version: 1.3
5  * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
6  *         Tobias Hößl <https://github.com/CatoTH/>
7  */
8
9 /**
10  * Installing the Friendica/Facebook connector
11  *
12  * Detailed instructions how to use this plugin can be found at
13  * https://github.com/friendica/friendica/wiki/How-to:-Friendica%E2%80%99s-Facebook-connector
14  *
15  * Vidoes and embeds will not be posted if there is no other content. Links 
16  * and images will be converted to a format suitable for the Facebook API and 
17  * long posts truncated - with a link to view the full post. 
18  *
19  * Facebook contacts will not be able to view private photos, as they are not able to
20  * authenticate to your site to establish identity. We will address this 
21  * in a future release.
22  */
23  
24  /** TODO
25  * - Implement a method for the administrator to delete all configuration data the plugin has created,
26  *   e.g. the app_access_token
27  */
28
29 // Size of maximum post length increased
30 // see http://www.facebook.com/schrep/posts/203969696349811
31 // define('FACEBOOK_MAXPOSTLEN', 420);
32 define('FACEBOOK_MAXPOSTLEN', 63206);
33 define('FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL', 259200); // 3 days
34 define('FACEBOOK_DEFAULT_POLL_INTERVAL', 60); // given in minutes
35 define('FACEBOOK_MIN_POLL_INTERVAL', 5);
36
37 require_once('include/security.php');
38
39 function facebook_install() {
40         register_hook('post_local',       'addon/facebook/facebook.php', 'facebook_post_local');
41         register_hook('notifier_normal',  'addon/facebook/facebook.php', 'facebook_post_hook');
42         register_hook('jot_networks',     'addon/facebook/facebook.php', 'facebook_jot_nets');
43         register_hook('connector_settings',  'addon/facebook/facebook.php', 'facebook_plugin_settings');
44         register_hook('cron',             'addon/facebook/facebook.php', 'facebook_cron');
45         register_hook('enotify',          'addon/facebook/facebook.php', 'facebook_enotify');
46         register_hook('queue_predeliver', 'addon/facebook/facebook.php', 'fb_queue_hook');
47 }
48
49
50 function facebook_uninstall() {
51         unregister_hook('post_local',       'addon/facebook/facebook.php', 'facebook_post_local');
52         unregister_hook('notifier_normal',  'addon/facebook/facebook.php', 'facebook_post_hook');
53         unregister_hook('jot_networks',     'addon/facebook/facebook.php', 'facebook_jot_nets');
54         unregister_hook('connector_settings',  'addon/facebook/facebook.php', 'facebook_plugin_settings');
55         unregister_hook('cron',             'addon/facebook/facebook.php', 'facebook_cron');
56         unregister_hook('enotify',          'addon/facebook/facebook.php', 'facebook_enotify');
57         unregister_hook('queue_predeliver', 'addon/facebook/facebook.php', 'fb_queue_hook');
58
59         // hook moved
60         unregister_hook('post_local_end',  'addon/facebook/facebook.php', 'facebook_post_hook');
61         unregister_hook('plugin_settings',  'addon/facebook/facebook.php', 'facebook_plugin_settings');
62 }
63
64
65 /* declare the facebook_module function so that /facebook url requests will land here */
66
67 function facebook_module() {}
68
69
70
71 // If a->argv[1] is a nickname, this is a callback from Facebook oauth requests.
72 // If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API
73
74 /**
75  * @param App $a
76  */
77 function facebook_init(&$a) {
78
79         if (x($_REQUEST, "realtime_cb") && x($_REQUEST, "realtime_cb")) {
80                 logger("facebook_init: Facebook Real-Time callback called", LOGGER_DEBUG);
81                 
82                 if (x($_REQUEST, "hub_verify_token")) {
83                         // this is the verification callback while registering for real time updates
84                         
85                         $verify_token = get_config('facebook', 'cb_verify_token');
86                         if ($verify_token != $_REQUEST["hub_verify_token"]) {
87                                 logger('facebook_init: Wrong Facebook Callback Verifier - expected ' . $verify_token . ', got ' . $_REQUEST["hub_verify_token"]);
88                                 return;
89                         }
90                         
91                         if (x($_REQUEST, "hub_challenge")) {
92                                 logger('facebook_init: Answering Challenge: ' . $_REQUEST["hub_challenge"], LOGGER_DATA);
93                                 echo $_REQUEST["hub_challenge"];
94                                 die();
95                         }
96                 }
97                 
98                 require_once('include/items.php');
99                 
100                 // this is a status update
101                 $content = file_get_contents("php://input");
102                 if (is_numeric($content)) $content = file_get_contents("php://input");
103                 $js = json_decode($content);
104                 logger(print_r($js, true), LOGGER_DATA);
105                 
106                 if (!isset($js->object) || $js->object != "user" || !isset($js->entry)) {
107                         logger('facebook_init: Could not parse Real-Time Update data', LOGGER_DEBUG);
108                         return;
109                 }
110                 
111                 $affected_users = array("feed" => array(), "friends" => array());
112                 
113                 foreach ($js->entry as $entry) {
114                         $fbuser = $entry->uid;
115                         foreach ($entry->changed_fields as $field) {
116                                 if (!isset($affected_users[$field])) {
117                                         logger('facebook_init: Unknown field "' . $field . '"');
118                                         continue;
119                                 }
120                                 if (in_array($fbuser, $affected_users[$field])) continue;
121                                 
122                                 $r = q("SELECT `uid` FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'self_id' AND `v` = '%s' LIMIT 1", dbesc($fbuser));
123                                 if(! count($r))
124                                         continue;
125                                 $uid = $r[0]['uid'];
126                                 
127                                 $access_token = get_pconfig($uid,'facebook','access_token');
128                                 if(! $access_token)
129                                         return;
130                                 
131                                 switch ($field) {
132                                         case "feed":
133                                                 logger('facebook_init: FB-User ' . $fbuser . ' / feed', LOGGER_DEBUG);
134                                                 
135                                                 if(! get_pconfig($uid,'facebook','no_wall')) {
136                                                         $private_wall = intval(get_pconfig($uid,'facebook','private_wall'));
137                                                         $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
138                                                         if($s) {
139                                                                 $j = json_decode($s);
140                                                                 if (isset($j->data)) {
141                                                                         logger('facebook_init: wall: ' . print_r($j,true), LOGGER_DATA);
142                                                                         fb_consume_stream($uid,$j,($private_wall) ? false : true);
143                                                                 } else {
144                                                                         logger('facebook_init: wall: got no data from Facebook: ' . print_r($j,true), LOGGER_NORMAL);
145                                                                 }
146                                                         }
147                                                 }
148                                                 
149                                         break;
150                                         case "friends":
151                                                 logger('facebook_init: FB-User ' . $fbuser . ' / friends', LOGGER_DEBUG);
152                                                 
153                                                 fb_get_friends($uid, false);
154                                                 set_pconfig($uid,'facebook','friend_check',time());
155                                         break;
156                                         default:
157                                                 logger('facebook_init: Unknown callback field for ' . $fbuser, LOGGER_NORMAL);
158                                 }
159                                 $affected_users[$field][] = $fbuser;
160                         }
161                 }
162         }
163
164         
165         if($a->argc != 2)
166                 return;
167         $nick = $a->argv[1];
168         if(strlen($nick))
169                 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
170                                 dbesc($nick)
171                 );
172         if(!(isset($r) && count($r)))
173                 return;
174
175         $uid           = $r[0]['uid'];
176         $auth_code     = (x($_GET, 'code') ? $_GET['code'] : '');
177         $error         = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
178
179
180         if($error)
181                 logger('facebook_init: Error: ' . $error);
182
183         if($auth_code && $uid) {
184
185                 $appid = get_config('facebook','appid');
186                 $appsecret = get_config('facebook', 'appsecret');
187
188                 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
189                         . $appid . '&client_secret=' . $appsecret . '&redirect_uri='
190                         . urlencode($a->get_baseurl() . '/facebook/' . $nick) 
191                         . '&code=' . $auth_code);
192
193                 logger('facebook_init: returned access token: ' . $x, LOGGER_DATA);
194
195                 if(strpos($x,'access_token=') !== false) {
196                         $token = str_replace('access_token=', '', $x);
197                         if(strpos($token,'&') !== false)
198                                 $token = substr($token,0,strpos($token,'&'));
199                         set_pconfig($uid,'facebook','access_token',$token);
200                         set_pconfig($uid,'facebook','post','1');
201                         if(get_pconfig($uid,'facebook','no_linking') === false)
202                                 set_pconfig($uid,'facebook','no_linking',1);
203                         fb_get_self($uid);
204                         fb_get_friends($uid, true);
205                         fb_consume_all($uid);
206
207                 }
208
209         }
210
211 }
212
213
214 /**
215  * @param int $uid
216  */
217 function fb_get_self($uid) {
218         $access_token = get_pconfig($uid,'facebook','access_token');
219         if(! $access_token)
220                 return;
221         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
222         if($s) {
223                 $j = json_decode($s);
224                 set_pconfig($uid,'facebook','self_id',(string) $j->id);
225         }
226 }
227
228 /**
229  * @param int $uid
230  * @param string $access_token
231  * @param array $persons
232  */
233 function fb_get_friends_sync_new($uid, $access_token, $persons) {
234     $persons_todo = array();
235     foreach ($persons as $person) {
236         $link = 'http://facebook.com/profile.php?id=' . $person->id;
237
238         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
239             intval($uid),
240             dbesc($link)
241         );
242
243         if (count($r) == 0) {
244             logger('fb_get_friends: new contact found: ' . $link, LOGGER_DEBUG);
245             $persons_todo[] = $person;
246         }
247
248         if (count($persons_todo) > 0) fb_get_friends_sync_full($uid, $access_token, $persons_todo);
249     }
250 }
251
252 /**
253  * @param int $uid
254  * @param object $contact
255  */
256 function fb_get_friends_sync_parsecontact($uid, $contact) {
257     $contact->link = 'http://facebook.com/profile.php?id=' . $contact->id;
258
259     // If its a page then set the first name from the username
260     if (!$contact->first_name and $contact->username)
261         $contact->first_name = $contact->username;
262
263     // check if we already have a contact
264
265     $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
266         intval($uid),
267         dbesc($contact->link)
268     );
269
270     if(count($r)) {
271
272         // check that we have all the photos, this has been known to fail on occasion
273
274         if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro'])) {
275             require_once("Photo.php");
276
277             $photos = import_profile_photo('https://graph.facebook.com/' . $contact->id . '/picture', $uid, $r[0]['id']);
278
279             q("UPDATE `contact` SET `photo` = '%s',
280                                         `thumb` = '%s',
281                                         `micro` = '%s',
282                                         `name-date` = '%s',
283                                         `uri-date` = '%s',
284                                         `avatar-date` = '%s'
285                                         WHERE `id` = %d LIMIT 1
286                                 ",
287                 dbesc($photos[0]),
288                 dbesc($photos[1]),
289                 dbesc($photos[2]),
290                 dbesc(datetime_convert()),
291                 dbesc(datetime_convert()),
292                 dbesc(datetime_convert()),
293                 intval($r[0]['id'])
294             );
295         }
296         return;
297     }
298     else {
299
300         // create contact record
301         q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
302                                 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
303                                 `writable`, `blocked`, `readonly`, `pending` )
304                                 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
305             intval($uid),
306             dbesc(datetime_convert()),
307             dbesc($contact->link),
308             dbesc(normalise_link($contact->link)),
309             dbesc(''),
310             dbesc(''),
311             dbesc($contact->id),
312             dbesc('facebook ' . $contact->id),
313             dbesc($contact->name),
314             dbesc(($contact->nickname) ? $contact->nickname : strtolower($contact->first_name)),
315             dbesc('https://graph.facebook.com/' . $contact->id . '/picture'),
316             dbesc(NETWORK_FACEBOOK),
317             intval(CONTACT_IS_FRIEND),
318             intval(1),
319             intval(1)
320         );
321     }
322
323     $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
324         dbesc($contact->link),
325         intval($uid)
326     );
327
328     if(! count($r)) {
329         return;
330     }
331
332     $contact_id  = $r[0]['id'];
333
334     require_once("Photo.php");
335
336     $photos = import_profile_photo($r[0]['photo'],$uid,$contact_id);
337
338     q("UPDATE `contact` SET `photo` = '%s',
339                         `thumb` = '%s',
340                         `micro` = '%s',
341                         `name-date` = '%s',
342                         `uri-date` = '%s',
343                         `avatar-date` = '%s'
344                         WHERE `id` = %d LIMIT 1
345                 ",
346         dbesc($photos[0]),
347         dbesc($photos[1]),
348         dbesc($photos[2]),
349         dbesc(datetime_convert()),
350         dbesc(datetime_convert()),
351         dbesc(datetime_convert()),
352         intval($contact_id)
353     );
354 }
355
356 /**
357  * @param int $uid
358  * @param string $access_token
359  * @param array $persons
360  */
361 function fb_get_friends_sync_full($uid, $access_token, $persons) {
362     if (count($persons) == 0) return;
363     $nums = Ceil(count($persons) / 50);
364     for ($i = 0; $i < $nums; $i++) {
365         $batch_request = array();
366         for ($j = $i * 50; $j < ($i+1) * 50 && $j < count($persons); $j++) $batch_request[] = array('method'=>'GET', 'relative_url'=>$persons[$j]->id);
367         $s = post_url('https://graph.facebook.com/', array('access_token' => $access_token, 'batch' => json_encode($batch_request)));
368         if($s) {
369             $results = json_decode($s);
370             logger('fb_get_friends: info: ' . print_r($results,true), LOGGER_DATA);
371             foreach ($results as $contact) {
372                 if ($contact->code != 200) logger('fb_get_friends: not found: ' . print_r($contact,true), LOGGER_DEBUG);
373                 else fb_get_friends_sync_parsecontact($uid, json_decode($contact->body));
374             }
375         }
376     }
377 }
378
379
380
381 // if $fullsync is true, only new contacts are searched for
382
383 /**
384  * @param int $uid
385  * @param bool $fullsync
386  */
387 function fb_get_friends($uid, $fullsync = true) {
388
389         $r = q("SELECT `uid` FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
390                 intval($uid)
391         );
392         if(! count($r))
393                 return;
394
395         $access_token = get_pconfig($uid,'facebook','access_token');
396
397         $no_linking = get_pconfig($uid,'facebook','no_linking');
398         if($no_linking)
399                 return;
400
401         if(! $access_token)
402                 return;
403         $s = fetch_url('https://graph.facebook.com/me/friends?access_token=' . $access_token);
404         if($s) {
405                 logger('facebook: fb_get_friends: ' . $s, LOGGER_DATA);
406                 $j = json_decode($s);
407                 logger('facebook: fb_get_friends: json: ' . print_r($j,true), LOGGER_DATA);
408                 if(! $j->data)
409                         return;
410
411             $persons_todo = array();
412         foreach($j->data as $person) $persons_todo[] = $person;
413
414         if ($fullsync)
415             fb_get_friends_sync_full($uid, $access_token, $persons_todo);
416         else
417             fb_get_friends_sync_new($uid, $access_token, $persons_todo);
418         }
419 }
420
421 // This is the POST method to the facebook settings page
422 // Content is posted to Facebook in the function facebook_post_hook() 
423
424 /**
425  * @param App $a
426  */
427 function facebook_post(&$a) {
428
429         $uid = local_user();
430         if($uid){
431
432                 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
433                 set_pconfig($uid,'facebook','post_by_default', $value);
434
435                 $no_linking = get_pconfig($uid,'facebook','no_linking');
436
437                 $no_wall = ((x($_POST,'facebook_no_wall')) ? intval($_POST['facebook_no_wall']) : 0);
438                 set_pconfig($uid,'facebook','no_wall',$no_wall);
439
440                 $private_wall = ((x($_POST,'facebook_private_wall')) ? intval($_POST['facebook_private_wall']) : 0);
441                 set_pconfig($uid,'facebook','private_wall',$private_wall);
442         
443
444                 set_pconfig($uid,'facebook','blocked_apps',escape_tags(trim($_POST['blocked_apps'])));
445
446                 $linkvalue = ((x($_POST,'facebook_linking')) ? intval($_POST['facebook_linking']) : 0);
447                 set_pconfig($uid,'facebook','no_linking', (($linkvalue) ? 0 : 1));
448
449                 // FB linkage was allowed but has just been turned off - remove all FB contacts and posts
450
451                 if((! intval($no_linking)) && (! intval($linkvalue))) {
452                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' ",
453                                 intval($uid),
454                                 dbesc(NETWORK_FACEBOOK)
455                         );
456                         if(count($r)) {
457                                 require_once('include/Contact.php');
458                                 foreach($r as $rr)
459                                         contact_remove($rr['id']);
460                         }
461                 }
462                 elseif(intval($no_linking) && intval($linkvalue)) {
463                         // FB linkage is now allowed - import stuff.
464                         fb_get_self($uid);
465                         fb_get_friends($uid, true);
466                         fb_consume_all($uid);
467                 }
468
469                 info( t('Settings updated.') . EOL);
470         } 
471
472         return;         
473 }
474
475 // Facebook settings form
476
477 /**
478  * @param App $a
479  * @return string
480  */
481 function facebook_content(&$a) {
482
483         if(! local_user()) {
484                 notice( t('Permission denied.') . EOL);
485                 return '';
486         }
487
488         if($a->argc > 1 && $a->argv[1] === 'remove') {
489                 del_pconfig(local_user(),'facebook','post');
490                 info( t('Facebook disabled') . EOL);
491         }
492
493         if($a->argc > 1 && $a->argv[1] === 'friends') {
494                 fb_get_friends(local_user(), true);
495                 info( t('Updating contacts') . EOL);
496         }
497
498         $o = '';
499         
500         $fb_installed = false;
501         if (get_pconfig(local_user(),'facebook','post')) {
502                 $access_token = get_pconfig(local_user(),'facebook','access_token');
503                 if ($access_token) {
504                         $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
505                         if($s) {
506                                 $j = json_decode($s);
507                                 if (isset($j->data)) $fb_installed = true;
508                         }
509                 }
510         }
511         
512         $appid = get_config('facebook','appid');
513
514         if(! $appid) {
515                 notice( t('Facebook API key is missing.') . EOL);
516                 return '';
517         }
518
519         $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
520                 . $a->get_baseurl() . '/addon/facebook/facebook.css' . '" media="all" />' . "\r\n";
521
522         $o .= '<h3>' . t('Facebook Connect') . '</h3>';
523
524         if(! $fb_installed) { 
525                 $o .= '<div id="facebook-enable-wrapper">';
526
527                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
528                         . $a->get_baseurl() . '/facebook/' . $a->user['nickname'] . '&scope=publish_stream,read_stream,offline_access">' . t('Install Facebook connector for this account.') . '</a>';
529                 $o .= '</div>';
530         }
531
532         if($fb_installed) {
533                 $o .= '<div id="facebook-disable-wrapper">';
534
535                 $o .= '<a href="' . $a->get_baseurl() . '/facebook/remove' . '">' . t('Remove Facebook connector') . '</a></div>';
536
537                 $o .= '<div id="facebook-enable-wrapper">';
538
539                 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
540                         . $a->get_baseurl() . '/facebook/' . $a->user['nickname'] . '&scope=publish_stream,read_stream,offline_access">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
541                 $o .= '</div>';
542         
543                 $o .= '<div id="facebook-post-default-form">';
544                 $o .= '<form action="facebook" method="post" >';
545                 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
546                 $checked = (($post_by_default) ? ' checked="checked" ' : '');
547                 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
548
549                 $no_linking = get_pconfig(local_user(),'facebook','no_linking');
550                 $checked = (($no_linking) ? '' : ' checked="checked" ');
551                 $o .= '<input type="checkbox" name="facebook_linking" value="1"' . $checked . '/>' . ' ' . t('Link all your Facebook friends and conversations on this website') . EOL ;
552
553                 $o .= '<p>' . t('Facebook conversations consist of your <em>profile wall</em> and your friend <em>stream</em>.');
554                 $o .= ' ' . t('On this website, your Facebook friend stream is only visible to you.');
555                 $o .= ' ' . t('The following settings determine the privacy of your Facebook profile wall on this website.') . '</p>';
556
557                 $private_wall = get_pconfig(local_user(),'facebook','private_wall');
558                 $checked = (($private_wall) ? ' checked="checked" ' : '');
559                 $o .= '<input type="checkbox" name="facebook_private_wall" value="1"' . $checked . '/>' . ' ' . t('On this website your Facebook profile wall conversations will only be visible to you') . EOL ;
560
561
562                 $no_wall = get_pconfig(local_user(),'facebook','no_wall');
563                 $checked = (($no_wall) ? ' checked="checked" ' : '');
564                 $o .= '<input type="checkbox" name="facebook_no_wall" value="1"' . $checked . '/>' . ' ' . t('Do not import your Facebook profile wall conversations') . EOL ;
565
566                 $o .= '<p>' . t('If you choose to link conversations and leave both of these boxes unchecked, your Facebook profile wall will be merged with your profile wall on this website and your privacy settings on this website will be used to determine who may see the conversations.') . '</p>';
567
568
569                 $blocked_apps = get_pconfig(local_user(),'facebook','blocked_apps');
570
571                 $o .= '<div><label id="blocked-apps-label" for="blocked-apps">' . t('Comma separated applications to ignore') . ' </label></div>';
572         $o .= '<div><textarea id="blocked-apps" name="blocked_apps" >' . htmlspecialchars($blocked_apps) . '</textarea></div>';
573
574                 $o .= '<input type="submit" name="submit" value="' . t('Submit') . '" /></form></div>';
575         }
576
577         return $o;
578 }
579
580
581 /**
582  * @param App $a
583  * @param null|object $b
584  * @return mixed
585  */
586 function facebook_cron($a,$b) {
587
588         $last = get_config('facebook','last_poll');
589         
590         $poll_interval = intval(get_config('facebook','poll_interval'));
591         if(! $poll_interval)
592                 $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
593
594         if($last) {
595                 $next = $last + $poll_interval;
596                 if($next > time()) 
597                         return;
598         }
599
600         logger('facebook_cron');
601
602
603         // Find the FB users on this site and randomize in case one of them
604         // uses an obscene amount of memory. It may kill this queue run
605         // but hopefully we'll get a few others through on each run. 
606
607         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'facebook' AND `k` = 'post' AND `v` = '1' ORDER BY RAND() ");
608         if(count($r)) {
609                 foreach($r as $rr) {
610                         if(get_pconfig($rr['uid'],'facebook','no_linking'))
611                                 continue;
612                         $ab = intval(get_config('system','account_abandon_days'));
613                         if($ab > 0) {
614                                 $z = q("SELECT `uid` FROM `user` WHERE `uid` = %d AND `login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY LIMIT 1",
615                                         intval($rr['uid']),
616                                         intval($ab)
617                                 );
618                                 if(! count($z))
619                                         continue;
620                         }
621
622                         // check for new friends once a day
623                         $last_friend_check = get_pconfig($rr['uid'],'facebook','friend_check');
624                         if($last_friend_check) 
625                                 $next_friend_check = $last_friend_check + 86400;
626                         else
627                             $next_friend_check = 0;
628                         if($next_friend_check <= time()) {
629                                 fb_get_friends($rr['uid'], true);
630                                 set_pconfig($rr['uid'],'facebook','friend_check',time());
631                         }
632                         fb_consume_all($rr['uid']);
633                 }
634         }
635         
636         if (get_config('facebook', 'realtime_active') == 1) {
637                 if (!facebook_check_realtime_active()) {
638                         
639                         logger('facebook_cron: Facebook is not sending Real-Time Updates any more, although it is supposed to. Trying to fix it...', LOGGER_NORMAL);
640                         facebook_subscription_add_users();
641                         
642                         if (facebook_check_realtime_active()) 
643                                 logger('facebook_cron: Successful', LOGGER_NORMAL);
644                         else {
645                                 logger('facebook_cron: Failed', LOGGER_NORMAL);
646                                 
647                                 if(strlen($a->config['admin_email']) && !get_config('facebook', 'realtime_err_mailsent')) {
648                                         mail($a->config['admin_email'], t('Problems with Facebook Real-Time Updates'),
649                                                 "Hi!\n\nThere's a problem with the Facebook Real-Time Updates that cannot be solved automatically. Maybe a permission issue?\n\nPlease try to re-activate it on " . $a->config["system"]["url"] . "/admin/plugins/facebook\n\nThis e-mail will only be sent once.",
650                                                 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
651                                                 . 'Content-type: text/plain; charset=UTF-8' . "\n"
652                                                 . 'Content-transfer-encoding: 8bit'
653                                         );
654                                         
655                                         set_config('facebook', 'realtime_err_mailsent', 1);
656                                 }
657                         }
658                 } else { // !facebook_check_realtime_active()
659                         del_config('facebook', 'realtime_err_mailsent');
660                 }
661         }
662         
663         set_config('facebook','last_poll', time());
664
665 }
666
667
668 /**
669  * @param App $a
670  * @param null|object $b
671  */
672 function facebook_plugin_settings(&$a,&$b) {
673
674         $b .= '<div class="settings-block">';
675         $b .= '<h3>' . t('Facebook') . '</h3>';
676         $b .= '<a href="facebook">' . t('Facebook Connector Settings') . '</a><br />';
677         $b .= '</div>';
678
679 }
680
681
682 /**
683  * @param App $a
684  * @param null|object $o
685  */
686 function facebook_plugin_admin(&$a, &$o){
687
688
689         $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
690         
691         $o .= '<h4>' . t('Facebook API Key') . '</h4>';
692         
693         $appid  = get_config('facebook', 'appid'  );
694         $appsecret = get_config('facebook', 'appsecret' );
695         $poll_interval = get_config('facebook', 'poll_interval' );
696         $sync_comments = get_config('facebook', 'sync_comments' );
697         if (!$poll_interval) $poll_interval = FACEBOOK_DEFAULT_POLL_INTERVAL;
698         
699         $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
700         $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
701         if ((count($ret1) > 0 && $ret1[0]['v'] != $appid) || (count($ret2) > 0 && $ret2[0]['v'] != $appsecret)) $o .= t('Error: it appears that you have specified the App-ID and -Secret in your .htconfig.php file. As long as they are specified there, they cannot be set using this form.<br><br>');
702         
703         $working_connection = false;
704         if ($appid && $appsecret) {
705                 $subs = facebook_subscriptions_get();
706                 if ($subs === null) $o .= t('Error: the given API Key seems to be incorrect (the application access token could not be retrieved).') . '<br>';
707                 elseif (is_array($subs)) {
708                         $o .= t('The given API Key seems to work correctly.') . '<br>';
709                         $working_connection = true;
710                 } else $o .= t('The correctness of the API Key could not be detected. Somthing strange\'s going on.') . '<br>';
711         }
712         
713         $o .= '<label for="fb_appid">' . t('App-ID / API-Key') . '</label><input name="appid" type="text" value="' . escape_tags($appid ? $appid : "") . '"><br style="clear: both;">';
714         $o .= '<label for="fb_appsecret">' . t('Application secret') . '</label><input name="appsecret" type="text" value="' . escape_tags($appsecret ? $appsecret : "") . '"><br style="clear: both;">';
715         $o .= '<label for="fb_poll_interval">' . sprintf(t('Polling Interval (min. %1$s minutes)'), FACEBOOK_MIN_POLL_INTERVAL) . '</label><input name="poll_interval" type="number" min="' . FACEBOOK_MIN_POLL_INTERVAL . '" value="' . $poll_interval . '"><br style="clear: both;">';
716         $o .= '<label for="fb_sync_comments">' . t('Synchronize comments (no comments on Facebook are missed, at the cost of increased system load)') . '</label><input name="sync_comments" id="fb_sync_comments" type="checkbox" ' . ($sync_comments ? 'checked' : '') . '><br style="clear: both;">';
717         $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
718         
719         if ($working_connection) {
720                 $o .= '<h4>' . t('Real-Time Updates') . '</h4>';
721                 
722                 $activated = facebook_check_realtime_active();
723                 if ($activated) {
724                         $o .= t('Real-Time Updates are activated.') . '<br><br>';
725                         $o .= '<input type="submit" name="real_time_deactivate" value="' . t('Deactivate Real-Time Updates') . '">';
726                 } else {
727                         $o .= t('Real-Time Updates not activated.') . '<br><input type="submit" name="real_time_activate" value="' . t('Activate Real-Time Updates') . '">';
728                 }
729         }
730 }
731
732 /**
733  * @param App $a
734  * @param null|object $o
735  */
736 function facebook_plugin_admin_post(&$a, &$o){
737         check_form_security_token_redirectOnErr('/admin/plugins/facebook', 'fbsave');
738         
739         if (x($_REQUEST,'fb_save_keys')) {
740                 set_config('facebook', 'appid', $_REQUEST['appid']);
741                 set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
742                 $poll_interval = IntVal($_REQUEST['poll_interval']);
743                 if ($poll_interval >= FACEBOOK_MIN_POLL_INTERVAL) set_config('facebook', 'poll_interval', $poll_interval);
744                 set_config('facebook', 'sync_comments', (x($_REQUEST, 'sync_comments') ? 1 : 0));
745                 del_config('facebook', 'app_access_token');
746                 info(t('The new values have been saved.'));
747         }
748         if (x($_REQUEST,'real_time_activate')) {
749                 facebook_subscription_add_users();
750         }
751         if (x($_REQUEST,'real_time_deactivate')) {
752                 facebook_subscription_del_users();
753         }
754 }
755
756 /**
757  * @param App $a
758  * @param object $b
759  * @return mixed
760  */
761 function facebook_jot_nets(&$a,&$b) {
762         if(! local_user())
763                 return;
764
765         $fb_post = get_pconfig(local_user(),'facebook','post');
766         if(intval($fb_post) == 1) {
767                 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
768                 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
769                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> ' 
770                         . t('Post to Facebook') . '</div>';     
771         }
772 }
773
774
775 /**
776  * @param App $a
777  * @param object $b
778  * @return mixed
779  */
780 function facebook_post_hook(&$a,&$b) {
781
782
783         if($b['deleted'] || ($b['created'] !== $b['edited']))
784                 return;
785
786         /**
787          * Post to Facebook stream
788          */
789
790         require_once('include/group.php');
791         require_once('include/html2plain.php');
792
793         logger('Facebook post');
794
795         $reply = false;
796         $likes = false;
797
798         $deny_arr = array();
799         $allow_arr = array();
800
801         $toplevel = (($b['id'] == $b['parent']) ? true : false);
802
803
804         $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
805
806         if((! $toplevel) && ($linking)) {
807                 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
808                         intval($b['parent']),
809                         intval($b['uid'])
810                 );
811                 if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
812                         $reply = substr($r[0]['uri'],4);
813                 elseif(count($r) && substr($r[0]['extid'],0,4) === 'fb::')
814                         $reply = substr($r[0]['extid'],4);
815                 else
816                         return;
817
818                 $u = q("SELECT * FROM user where uid = %d limit 1",
819                         intval($b['uid'])
820                 );
821                 if(! count($u))
822                         return;
823
824                 // only accept comments from the item owner. Other contacts are unknown to FB.
825  
826                 if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
827                         return;
828                 
829
830                 logger('facebook reply id=' . $reply);
831         }
832
833         if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
834
835                 if($b['private'] && $reply === false) {
836                         $allow_people = expand_acl($b['allow_cid']);
837                         $allow_groups = expand_groups(expand_acl($b['allow_gid']));
838                         $deny_people  = expand_acl($b['deny_cid']);
839                         $deny_groups  = expand_groups(expand_acl($b['deny_gid']));
840
841                         $recipients = array_unique(array_merge($allow_people,$allow_groups));
842                         $deny = array_unique(array_merge($deny_people,$deny_groups));
843
844                         $allow_str = dbesc(implode(', ',$recipients));
845                         if($allow_str) {
846                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'"); 
847                                 if(count($r))
848                                         foreach($r as $rr)
849                                                 $allow_arr[] = $rr['notify'];
850                         }
851
852                         $deny_str = dbesc(implode(', ',$deny));
853                         if($deny_str) {
854                                 $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'"); 
855                                 if(count($r))
856                                         foreach($r as $rr)
857                                                 $deny_arr[] = $rr['notify'];
858                         }
859
860                         if(count($deny_arr) && (! count($allow_arr))) {
861
862                                 // One or more FB folks were denied access but nobody on FB was specifically allowed access.
863                                 // This might cause the post to be open to public on Facebook, but only to selected members
864                                 // on another network. Since this could potentially leak a post to somebody who was denied, 
865                                 // we will skip posting it to Facebook with a slightly vague but relevant message that will 
866                                 // hopefully lead somebody to this code comment for a better explanation of what went wrong.
867
868                                 notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
869                                 return;
870                         }
871
872
873                         // if it's a private message but no Facebook members are allowed or denied, skip Facebook post
874
875                         if((! count($allow_arr)) && (! count($deny_arr)))
876                                 return;
877                 }
878
879                 if($b['verb'] == ACTIVITY_LIKE)
880                         $likes = true;                          
881
882
883                 $appid  = get_config('facebook', 'appid'  );
884                 $secret = get_config('facebook', 'appsecret' );
885
886                 if($appid && $secret) {
887
888                         logger('facebook: have appid+secret');
889
890                         $fb_token  = get_pconfig($b['uid'],'facebook','access_token');
891
892
893                         // post to facebook if it's a public post and we've ticked the 'post to Facebook' box, 
894                         // or it's a private message with facebook participants
895                         // or it's a reply or likes action to an existing facebook post                 
896
897                         if($fb_token && ($toplevel || $b['private'] || $reply)) {
898                                 logger('facebook: able to post');
899                                 require_once('library/facebook.php');
900                                 require_once('include/bbcode.php');     
901
902                                 $msg = $b['body'];
903
904                                 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
905
906                                 // make links readable before we strip the code
907
908                                 // unless it's a dislike - just send the text as a comment
909
910                                 // if($b['verb'] == ACTIVITY_DISLIKE)
911                                 //      $msg = trim(strip_tags(bbcode($msg)));
912
913                                 // Old code
914                                 /*$search_str = $a->get_baseurl() . '/search';
915
916                                 if(preg_match("/\[url=(.*?)\](.*?)\[\/url\]/is",$msg,$matches)) {
917
918                                         // don't use hashtags for message link
919
920                                         if(strpos($matches[2],$search_str) === false) {
921                                                 $link = $matches[1];
922                                                 if(substr($matches[2],0,5) != '[img]')
923                                                         $linkname = $matches[2];
924                                         }
925                                 }
926
927                                 // strip tag links to avoid link clutter, this really should be 
928                                 // configurable because we're losing information
929
930                                 $msg = preg_replace("/\#\[url=(.*?)\](.*?)\[\/url\]/is",'#$2',$msg);
931
932                                 // provide the link separately for normal links
933                                 $msg = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is",'$2 $1',$msg);
934
935                                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$msg,$matches))
936                                         $image = $matches[1];
937
938                                 $msg = preg_replace("/\[img\](.*?)\[\/img\]/is", t('Image: ') . '$1', $msg);
939
940                                 if((strpos($link,z_root()) !== false) && (! $image))
941                                         $image = $a->get_baseurl() . '/images/friendica-64.jpg';
942
943                                 $msg = trim(strip_tags(bbcode($msg)));*/
944
945                                 // New code
946
947                                 // Looking for the first image
948                                 $image = '';
949                                 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
950                                         $image = $matches[3];
951
952                                 if ($image == '')
953                                         if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
954                                                 $image = $matches[1];
955
956                                 // Checking for a bookmark element
957                                 $body = $b['body'];
958                                 if (strpos($body, "[bookmark") !== false) {
959                                         // splitting the text in two parts:
960                                         // before and after the bookmark
961                                         $pos = strpos($body, "[bookmark");
962                                         $body1 = substr($body, 0, $pos);
963                                         $body2 = substr($body, $pos);
964
965                                         // Removing the bookmark and all quotes after the bookmark
966                                         // they are mostly only the content after the bookmark.
967                                         $body2 = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'',$body2);
968                                         $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
969                                         $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
970
971                                         $body = $body1.$body2;
972                                 }
973
974                                 // At first convert the text to html
975                                 $html = bbcode($body);
976
977                                 // Then convert it to plain text
978                                 $msg = trim($b['title']." \n\n".html2plain($html, 0, true));
979                                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
980
981                                 // Removing multiple newlines
982                                 while (strpos($msg, "\n\n\n") !== false)
983                                         $msg = str_replace("\n\n\n", "\n\n", $msg);
984
985                                 // add any attachments as text urls
986                                 $arr = explode(',',$b['attach']);
987
988                                 if(count($arr)) {
989                                         $msg .= "\n";
990                                         foreach($arr as $r) {
991                                                 $matches = false;
992                                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
993                                                 if($cnt) {
994                                                         $msg .= "\n".$matches[1];
995                                                 }
996                                         }
997                                 }
998
999                                 $link = '';
1000                                 $linkname = '';
1001                                 // look for bookmark-bbcode and handle it with priority
1002                                 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
1003                                         $link = $matches[1];
1004                                         $linkname = $matches[2];
1005                                 }
1006
1007                                 // If there is no bookmark element then take the first link
1008                                 if ($link == '') {
1009                                         $links = collecturls($html);
1010                                         if (sizeof($links) > 0) {
1011                                                 reset($links);
1012                                                 $link = current($links);
1013                                         }
1014                                 }
1015
1016                                 // Remove trailing and leading spaces
1017                                 $msg = trim($msg);
1018
1019                                 // Since facebook increased the maxpostlen massively this never should happen again :)
1020                                 if (strlen($msg) > FACEBOOK_MAXPOSTLEN) {
1021                                         require_once('library/slinky.php');
1022
1023                                         $display_url = $b['plink'];
1024
1025                                         $slinky = new Slinky( $display_url );
1026                                         // setup a cascade of shortening services
1027                                         // try to get a short link from these services
1028                                         // in the order ur1.ca, trim, id.gd, tinyurl
1029                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
1030                                         $shortlink = $slinky->short();
1031                                         // the new message will be shortened such that "... $shortlink"
1032                                         // will fit into the character limit
1033                                         $msg = substr($msg, 0, FACEBOOK_MAXPOSTLEN - strlen($shortlink) - 4);
1034                                         $msg .= '... ' . $shortlink;
1035                                 }
1036
1037                                 // Fallback - if message is empty
1038                                 if(!strlen($msg))
1039                                         $msg = $link;
1040
1041                                 if(!strlen($msg))
1042                                         $msg = $image;
1043
1044                                 if(!strlen($msg))
1045                                         $msg = $linkname;
1046
1047                                 // If there is nothing to post then exit
1048                                 if(!strlen($msg))
1049                                         return;
1050
1051                                 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
1052
1053                                 if($likes) { 
1054                                         $postvars = array('access_token' => $fb_token);
1055                                 }
1056                                 else {
1057                                         $postvars = array(
1058                                                 'access_token' => $fb_token, 
1059                                                 'message' => $msg
1060                                         );
1061                                         if(isset($image)) {
1062                                                 $postvars['picture'] = $image;
1063                                                 //$postvars['type'] = "photo";
1064                                         }
1065                                         if(isset($link)) {
1066                                                 $postvars['link'] = $link;
1067                                                 //$postvars['type'] = "link";
1068                                         }
1069                                         if(isset($linkname))
1070                                                 $postvars['name'] = $linkname;
1071                                 }
1072
1073                                 if(($b['private']) && ($toplevel)) {
1074                                         $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
1075                                         if(count($allow_arr))
1076                                                 $postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
1077                                         if(count($deny_arr))
1078                                                 $postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
1079                                         $postvars['privacy'] .= '}';
1080
1081                                 }
1082
1083                                 if($reply) {
1084                                         $url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
1085                                 } else if (($link != "")  or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) { 
1086                                         $url = 'https://graph.facebook.com/me/feed';
1087                                         if($b['plink'])
1088                                                 $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' .  $b['plink'] . '"}';
1089                                 } else {
1090                                         // if its only a message and a subject and the message is larger than 500 characters then post it as note
1091                                         $postvars = array(
1092                                                 'access_token' => $fb_token, 
1093                                                 'message' => bbcode($b['body']),
1094                                                 'subject' => $b['title'],
1095                                         );
1096                                         $url = 'https://graph.facebook.com/me/notes';
1097                                 }
1098
1099                                 logger('facebook: post to ' . $url);
1100                                 logger('facebook: postvars: ' . print_r($postvars,true));
1101
1102                                 // "test_mode" prevents anything from actually being posted.
1103                                 // Otherwise, let's do it.
1104
1105                                 if(! get_config('facebook','test_mode')) {
1106                                         $x = post_url($url, $postvars);
1107                                         logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
1108
1109                                         $retj = json_decode($x);
1110                                         if($retj->id) {
1111                                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
1112                                                         dbesc('fb::' . $retj->id),
1113                                                         intval($b['id'])
1114                                                 );
1115                                         }
1116                                         else {
1117                                                 if(! $likes) {
1118                                                         $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
1119                                                         require_once('include/queue_fn.php');
1120                                                         add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
1121                                                         notice( t('Facebook post failed. Queued for retry.') . EOL);
1122                                                 }
1123                                                 
1124                                                 if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
1125                                                         logger('Facebook session has expired due to changed password.', LOGGER_DEBUG);
1126                                                         
1127                                                         $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
1128                                                         if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
1129                                                                 require_once('include/enotify.php');
1130                                                         
1131                                                                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']) );
1132                                                                 notification(array(
1133                                                                         'uid' => $b['uid'],
1134                                                                         'type' => NOTIFY_SYSTEM,
1135                                                                         'system_type' => 'facebook_connection_invalid',
1136                                                                         'language'     => $r[0]['language'],
1137                                                                         'to_name'      => $r[0]['username'],
1138                                                                         'to_email'     => $r[0]['email'],
1139                                                                         'source_name'  => t('Administrator'),
1140                                                                         'source_link'  => $a->config["system"]["url"],
1141                                                                         'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
1142                                                                 ));
1143                                                                 
1144                                                                 set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
1145                                                         } else logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
1146                                                 }
1147                                         }
1148                                 }
1149                         }
1150                 }
1151         }
1152 }
1153
1154 /**
1155  * @param App $app
1156  * @param object $data
1157  */
1158 function facebook_enotify(&$app, &$data) {
1159         if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
1160                 $data['itemlink'] = '/facebook';
1161                 $data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
1162                 $data['subject'] = t('Facebook connection became invalid');
1163                 $data['body'] = sprintf( t("Hi %1\$s,\n\nThe connection between your accounts on %2\$s and Facebook became invalid. This usually happens after you change your Facebook-password. To enable the connection again, you have to %3\$sre-authenticate the Facebook-connector%4\$s."), $data['params']['to_name'], "[url=" . $app->config["system"]["url"] . "]" . $app->config["sitename"] . "[/url]", "[url=" . $app->config["system"]["url"] . "/facebook]", "[/url]");
1164         }
1165 }
1166
1167 /**
1168  * @param App $a
1169  * @param object $b
1170  */
1171 function facebook_post_local(&$a,&$b) {
1172
1173         // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
1174         // where we will discover it during background delivery.
1175
1176         // This can only be triggered by a local user posting to their own wall.
1177
1178         if((local_user()) && (local_user() == $b['uid'])) {
1179
1180                 $fb_post   = intval(get_pconfig(local_user(),'facebook','post'));
1181                 $fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
1182
1183                 // if API is used, default to the chosen settings
1184                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default')))
1185                         $fb_enable = 1;
1186
1187                 if(! $fb_enable)
1188                         return;
1189
1190                 if(strlen($b['postopts']))
1191                         $b['postopts'] .= ',';
1192                 $b['postopts'] .= 'facebook';
1193         }
1194 }
1195
1196
1197 /**
1198  * @param App $a
1199  * @param object $b
1200  */
1201 function fb_queue_hook(&$a,&$b) {
1202
1203         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1204                 dbesc(NETWORK_FACEBOOK)
1205         );
1206         if(! count($qi))
1207                 return;
1208
1209         require_once('include/queue_fn.php');
1210
1211         foreach($qi as $x) {
1212                 if($x['network'] !== NETWORK_FACEBOOK)
1213                         continue;
1214
1215                 logger('facebook_queue: run');
1216
1217                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
1218                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1219                         intval($x['cid'])
1220                 );
1221                 if(! count($r))
1222                         continue;
1223
1224                 $user = $r[0];
1225
1226                 $appid  = get_config('facebook', 'appid'  );
1227                 $secret = get_config('facebook', 'appsecret' );
1228
1229                 if($appid && $secret) {
1230                         $fb_post   = intval(get_pconfig($user['uid'],'facebook','post'));
1231                         $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
1232
1233                         if($fb_post && $fb_token) {
1234                                 logger('facebook_queue: able to post');
1235                                 require_once('library/facebook.php');
1236
1237                                 $z = unserialize($x['content']);
1238                                 $item = $z['item'];
1239                                 $j = post_url($z['url'],$z['post']);
1240
1241                                 $retj = json_decode($j);
1242                                 if($retj->id) {
1243                                         q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
1244                                                 dbesc('fb::' . $retj->id),
1245                                                 intval($item)
1246                                         );
1247                                         logger('facebook_queue: success: ' . $j); 
1248                                         remove_queue_item($x['id']);
1249                                 }
1250                                 else {
1251                                         logger('facebook_queue: failed: ' . $j);
1252                                         update_queue_time($x['id']);
1253                                 }
1254                         }
1255                 }
1256         }
1257 }
1258
1259 /**
1260  * @param string $access_token
1261  * @param int $since
1262  * @return object
1263  */
1264 function fb_get_timeline($access_token, &$since) {
1265
1266     $entries = new stdClass();
1267         $entries->data = array();
1268         $newest = 0;
1269
1270         $url = 'https://graph.facebook.com/me/home?access_token='.$access_token;
1271
1272         if ($since != 0)
1273                 $url .= "&since=".$since;
1274
1275         do {
1276                 $s = fetch_url($url);
1277                 $j = json_decode($s);
1278                 $oldestdate = time();
1279                 if (isset($j->data))
1280                         foreach ($j->data as $entry) {
1281                                 $created = strtotime($entry->created_time);
1282
1283                                 if ($newest < $created)
1284                                         $newest = $created;
1285
1286                                 if ($created >= $since)
1287                                         $entries->data[] = $entry;
1288
1289                                 if ($created <= $oldestdate)
1290                                         $oldestdate = $created;
1291                         }
1292                 else
1293                         break;
1294
1295                 $url = (isset($j->paging) && isset($j->paging->next) ? $j->paging->next : '');
1296
1297         } while (($oldestdate > $since) and ($since != 0) and ($url != ''));
1298
1299         if ($newest > $since)
1300                 $since = $newest;
1301
1302         return($entries);
1303 }
1304
1305 /**
1306  * @param int $uid
1307  */
1308 function fb_consume_all($uid) {
1309
1310         require_once('include/items.php');
1311
1312         $access_token = get_pconfig($uid,'facebook','access_token');
1313         if(! $access_token)
1314                 return;
1315         
1316         if(! get_pconfig($uid,'facebook','no_wall')) {
1317                 $private_wall = intval(get_pconfig($uid,'facebook','private_wall'));
1318                 $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
1319                 if($s) {
1320                         $j = json_decode($s);
1321                         if (isset($j->data)) {
1322                                 logger('fb_consume_stream: wall: ' . print_r($j,true), LOGGER_DATA);
1323                                 fb_consume_stream($uid,$j,($private_wall) ? false : true);
1324                         } else {
1325                                 logger('fb_consume_stream: wall: got no data from Facebook: ' . print_r($j,true), LOGGER_NORMAL);
1326                         }
1327                 }
1328         }
1329         // Get the last date
1330         $lastdate = get_pconfig($uid,'facebook','lastdate') - 10000;
1331         // fetch all items since the last date
1332         $j = fb_get_timeline($access_token, $lastdate);
1333         if (isset($j->data)) {
1334                 logger('fb_consume_stream: feed: ' . print_r($j,true), LOGGER_DATA);
1335                 fb_consume_stream($uid,$j,false);
1336
1337                 // Write back the last date
1338                 set_pconfig($uid,'facebook','lastdate', $lastdate);
1339         } else
1340                 logger('fb_consume_stream: feed: got no data from Facebook: ' . print_r($j,true), LOGGER_NORMAL);
1341 }
1342
1343 /**
1344  * @param int $uid
1345  * @param string $link
1346  * @return string
1347  */
1348 function fb_get_photo($uid,$link) {
1349         $access_token = get_pconfig($uid,'facebook','access_token');
1350         if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
1351                 return "";
1352                 //return "\n" . '[url=' . $link . ']' . t('link') . '[/url]';
1353         $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
1354         if($ret)
1355                 $photo_id = $match[1];
1356         else
1357             return "";
1358         $x = fetch_url('https://graph.facebook.com/' . $photo_id . '?access_token=' . $access_token);
1359         $j = json_decode($x);
1360         if($j->picture)
1361                 return "\n\n" . '[url=' . $link . '][img]' . $j->picture . '[/img][/url]';
1362         //else
1363         //      return "\n" . '[url=' . $link . ']' . t('link') . '[/url]';
1364         return "";
1365 }
1366
1367
1368 /**
1369  * @param App $a
1370  * @param array $user
1371  * @param array $self
1372  * @param string $fb_id
1373  * @param bool $wall
1374  * @param array $orig_post
1375  * @param object $cmnt
1376  */
1377 function fb_consume_comment(&$a, &$user, &$self, $fb_id, $wall, &$orig_post, &$cmnt) {
1378
1379     if(! $orig_post)
1380         return;
1381
1382     $top_item = $orig_post['id'];
1383     $uid = IntVal($user[0]['uid']);
1384
1385     $r = q("SELECT * FROM `item` WHERE `uid` = %d AND ( `uri` = '%s' OR `extid` = '%s' ) LIMIT 1",
1386         intval($uid),
1387         dbesc('fb::' . $cmnt->id),
1388         dbesc('fb::' . $cmnt->id)
1389     );
1390     if(count($r))
1391         return;
1392
1393     $cmntdata = array();
1394     $cmntdata['parent'] = $top_item;
1395     $cmntdata['verb'] = ACTIVITY_POST;
1396     $cmntdata['gravity'] = 6;
1397     $cmntdata['uid'] = $uid;
1398     $cmntdata['wall'] = (($wall) ? 1 : 0);
1399     $cmntdata['uri'] = 'fb::' . $cmnt->id;
1400     $cmntdata['parent-uri'] = $orig_post['uri'];
1401     if($cmnt->from->id == $fb_id) {
1402         $cmntdata['contact-id'] = $self[0]['id'];
1403     }
1404     else {
1405         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
1406             dbesc($cmnt->from->id),
1407             intval($uid)
1408         );
1409         if(count($r)) {
1410             $cmntdata['contact-id'] = $r[0]['id'];
1411             if($r[0]['blocked'] || $r[0]['readonly'])
1412                 return;
1413         }
1414     }
1415     if(! x($cmntdata,'contact-id'))
1416         $cmntdata['contact-id'] = $orig_post['contact-id'];
1417
1418     $cmntdata['app'] = 'facebook';
1419     $cmntdata['created'] = datetime_convert('UTC','UTC',$cmnt->created_time);
1420     $cmntdata['edited']  = datetime_convert('UTC','UTC',$cmnt->created_time);
1421     $cmntdata['verb'] = ACTIVITY_POST;
1422     $cmntdata['author-name'] = $cmnt->from->name;
1423     $cmntdata['author-link'] = 'http://facebook.com/profile.php?id=' . $cmnt->from->id;
1424     $cmntdata['author-avatar'] = 'https://graph.facebook.com/' . $cmnt->from->id . '/picture';
1425     $cmntdata['body'] = $cmnt->message;
1426     $item = item_store($cmntdata);
1427
1428     $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
1429         dbesc($orig_post['uri']),
1430         intval($uid)
1431     );
1432
1433     if(count($myconv)) {
1434         $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1435
1436         foreach($myconv as $conv) {
1437
1438             // now if we find a match, it means we're in this conversation
1439
1440             if(! link_compare($conv['author-link'],$importer_url))
1441                 continue;
1442
1443             require_once('include/enotify.php');
1444
1445             $conv_parent = $conv['parent'];
1446
1447             notification(array(
1448                 'type'         => NOTIFY_COMMENT,
1449                 'notify_flags' => $user[0]['notify-flags'],
1450                 'language'     => $user[0]['language'],
1451                 'to_name'      => $user[0]['username'],
1452                 'to_email'     => $user[0]['email'],
1453                 'uid'          => $user[0]['uid'],
1454                 'item'         => $cmntdata,
1455                 'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
1456                 'source_name'  => $cmntdata['author-name'],
1457                 'source_link'  => $cmntdata['author-link'],
1458                 'source_photo' => $cmntdata['author-avatar'],
1459                 'verb'         => ACTIVITY_POST,
1460                 'otype'        => 'item',
1461                 'parent'       => $conv_parent,
1462             ));
1463
1464             // only send one notification
1465             break;
1466         }
1467     }
1468 }
1469
1470
1471 /**
1472  * @param App $a
1473  * @param array $user
1474  * @param array $self
1475  * @param string $fb_id
1476  * @param bool $wall
1477  * @param array $orig_post
1478  * @param object $likes
1479  */
1480 function fb_consume_like(&$a, &$user, &$self, $fb_id, $wall, &$orig_post, &$likes) {
1481
1482     $top_item = $orig_post['id'];
1483     $uid = IntVal($user[0]['uid']);
1484
1485     if(! $orig_post)
1486         return;
1487
1488     // If we posted the like locally, it will be found with our url, not the FB url.
1489
1490     $second_url = (($likes->id == $fb_id) ? $self[0]['url'] : 'http://facebook.com/profile.php?id=' . $likes->id);
1491
1492     $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
1493         AND ( `author-link` = '%s' OR `author-link` = '%s' ) LIMIT 1",
1494         dbesc($orig_post['uri']),
1495         intval($uid),
1496         dbesc(ACTIVITY_LIKE),
1497         dbesc('http://facebook.com/profile.php?id=' . $likes->id),
1498         dbesc($second_url)
1499     );
1500
1501     if(count($r))
1502         return;
1503
1504     $likedata = array();
1505     $likedata['parent'] = $top_item;
1506     $likedata['verb'] = ACTIVITY_LIKE;
1507     $likedata['gravity'] = 3;
1508     $likedata['uid'] = $uid;
1509     $likedata['wall'] = (($wall) ? 1 : 0);
1510     $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
1511     $likedata['parent-uri'] = $orig_post['uri'];
1512     if($likes->id == $fb_id)
1513         $likedata['contact-id'] = $self[0]['id'];
1514     else {
1515         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1516             dbesc($likes->id),
1517             intval($uid)
1518         );
1519         if(count($r))
1520             $likedata['contact-id'] = $r[0]['id'];
1521     }
1522     if(! x($likedata,'contact-id'))
1523         $likedata['contact-id'] = $orig_post['contact-id'];
1524
1525     $likedata['app'] = 'facebook';
1526     $likedata['verb'] = ACTIVITY_LIKE;
1527     $likedata['author-name'] = $likes->name;
1528     $likedata['author-link'] = 'http://facebook.com/profile.php?id=' . $likes->id;
1529     $likedata['author-avatar'] = 'https://graph.facebook.com/' . $likes->id . '/picture';
1530
1531     $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
1532     $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
1533     $post_type = t('status');
1534     $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
1535     $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
1536
1537     $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
1538     $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
1539         '<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>';
1540
1541     item_store($likedata);
1542 }
1543
1544 /**
1545  * @param App $a
1546  * @param array $user
1547  * @param object $entry
1548  * @param array $self
1549  * @param string $fb_id
1550  * @param bool $wall
1551  * @param array $orig_post
1552  */
1553 function fb_consume_status(&$a, &$user, &$entry, &$self, $fb_id, $wall, &$orig_post) {
1554     $uid = IntVal($user[0]['uid']);
1555     $access_token = get_pconfig($uid, 'facebook', 'access_token');
1556
1557     $s = fetch_url('https://graph.facebook.com/' . $entry->id . '?access_token=' . $access_token);
1558     if($s) {
1559         $j = json_decode($s);
1560         if (isset($j->comments) && isset($j->comments->data))
1561             foreach ($j->comments->data as $cmnt)
1562                 fb_consume_comment($a, $user, $self, $fb_id, $wall, $orig_post, $cmnt);
1563
1564         if (isset($j->likes) && isset($j->likes->data))
1565             foreach ($j->likes->data as $likers)
1566                 fb_consume_like($a, $user, $self, $fb_id, $wall, $orig_post, $likers);
1567     }
1568 }
1569
1570 /**
1571  * @param int $uid
1572  * @param object $j
1573  * @param bool $wall
1574  */
1575 function fb_consume_stream($uid,$j,$wall = false) {
1576
1577         $a = get_app();
1578
1579         $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1580                 intval($uid)
1581         );
1582         if(! count($user))
1583                 return;
1584
1585         // $my_local_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
1586
1587         $no_linking = get_pconfig($uid,'facebook','no_linking');
1588         if($no_linking)
1589                 return;
1590
1591         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1592                 intval($uid)
1593         );
1594
1595         $blocked_apps = get_pconfig($uid,'facebook','blocked_apps');
1596         $blocked_apps_arr = explode(',',$blocked_apps);
1597
1598         $sync_comments = get_config('facebook', 'sync_comments');
1599
1600     /** @var string $self_id  */
1601         $self_id = get_pconfig($uid,'facebook','self_id');
1602         if(! count($j->data) || (! strlen($self_id)))
1603                 return;
1604
1605     $top_item = 0;
1606
1607     foreach($j->data as $entry) {
1608                 logger('fb_consume: entry: ' . print_r($entry,true), LOGGER_DATA);
1609                 $datarray = array();
1610
1611                 $r = q("SELECT * FROM `item` WHERE ( `uri` = '%s' OR `extid` = '%s') AND `uid` = %d LIMIT 1",
1612                                 dbesc('fb::' . $entry->id),
1613                                 dbesc('fb::' . $entry->id),
1614                                 intval($uid)
1615                 );
1616                 if(count($r)) {
1617                         $orig_post = $r[0];
1618                         $top_item = $r[0]['id'];
1619                 }
1620                 else {
1621                         $orig_post = null;
1622                 }
1623
1624                 if(! $orig_post) {
1625                         $datarray['gravity'] = 0;
1626                         $datarray['uid'] = $uid;
1627                         $datarray['wall'] = (($wall) ? 1 : 0);
1628                         $datarray['uri'] = $datarray['parent-uri'] = 'fb::' . $entry->id;
1629                         $from = $entry->from;
1630                         if($from->id == $self_id)
1631                                 $datarray['contact-id'] = $self[0]['id'];
1632                         else {
1633                                 // Looking if user is known - if not he is added
1634                                 $access_token = get_pconfig($uid, 'facebook', 'access_token');
1635                                 fb_get_friends_sync_new($uid, $access_token, array($from));
1636
1637                                 $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d AND `blocked` = 0 AND `readonly` = 0 LIMIT 1",
1638                                         dbesc($from->id),
1639                                         intval($uid)
1640                                 );
1641                                 if(count($r))
1642                                         $datarray['contact-id'] = $r[0]['id'];
1643                         }
1644
1645                         // don't store post if we don't have a contact
1646                         if(! x($datarray,'contact-id')) {
1647                                 logger('facebook: no contact '.$from->name.' '.$from->id.'. post ignored');
1648                                 continue;
1649                         }
1650
1651                         $datarray['verb'] = ACTIVITY_POST;
1652                         if($wall) {
1653                                 $datarray['owner-name'] = $self[0]['name'];
1654                                 $datarray['owner-link'] = $self[0]['url'];
1655                                 $datarray['owner-avatar'] = $self[0]['thumb'];
1656                         }
1657                         if(isset($entry->application) && isset($entry->application->name) && strlen($entry->application->name))
1658                                 $datarray['app'] = strip_tags($entry->application->name);
1659                         else
1660                                 $datarray['app'] = 'facebook';
1661
1662                         $found_blocked = false;
1663
1664                         if(count($blocked_apps_arr)) {
1665                                 foreach($blocked_apps_arr as $bad_appl) {
1666                                         if(strlen(trim($bad_appl)) && (stristr($datarray['app'],trim($bad_appl)))) {
1667                                                 $found_blocked = true;
1668                                         }
1669                                 }
1670                         }
1671                                 
1672                         if($found_blocked) {
1673                                 logger('facebook: blocking application: ' . $datarray['app']);
1674                                 continue;
1675                         }
1676
1677                         $datarray['author-name'] = $from->name;
1678                         $datarray['author-link'] = 'http://facebook.com/profile.php?id=' . $from->id;
1679                         $datarray['author-avatar'] = 'https://graph.facebook.com/' . $from->id . '/picture';
1680                         $datarray['plink'] = $datarray['author-link'] . '&v=wall&story_fbid=' . substr($entry->id,strpos($entry->id,'_') + 1);
1681
1682                         logger('facebook: post '.$entry->id.' from '.$from->name);
1683
1684                         $datarray['body'] = (isset($entry->message) ? escape_tags($entry->message) : '');
1685
1686                         if(isset($entry->name) and isset($entry->link))
1687                                 $datarray['body'] .= "\n\n[bookmark=".$entry->link."]".$entry->name."[/bookmark]";
1688                         elseif (isset($entry->name))
1689                                 $datarray['body'] .= "\n\n[b]" . $entry->name."[/b]";
1690
1691                         if(isset($entry->caption)) {
1692                                 if(!isset($entry->name) and isset($entry->link))
1693                                         $datarray['body'] .= "\n\n[bookmark=".$entry->link."]".$entry->caption."[/bookmark]";
1694                                 else
1695                                         $datarray['body'] .= "[i]" . $entry->caption."[/i]\n";
1696                         }
1697
1698                         if(!isset($entry->caption) and !isset($entry->name)) {
1699                                 if (isset($entry->link))
1700                                         $datarray['body'] .= "\n[url]".$entry->link."[/url]\n";
1701                                 else
1702                                         $datarray['body'] .= "\n";
1703                         }
1704
1705                         $quote = "";
1706                         if(isset($entry->description))
1707                                 $quote = $entry->description;
1708
1709                         if (isset($entry->properties))
1710                                 foreach ($entry->properties as $property)
1711                                         $quote .= "\n".$property->name.": [url=".$property->href."]".$property->text."[/url]";
1712
1713                         if ($quote)
1714                                 $datarray['body'] .= "\n[quote]".$quote."[/quote]";
1715
1716                         // Only import the picture when the message is no video
1717                         // oembed display a picture of the video as well 
1718                         if ($entry->type != "video") {
1719                                 if(isset($entry->picture) && isset($entry->link)) {
1720                                         $datarray['body'] .= "\n" . '[url=' . $entry->link . '][img]'.$entry->picture.'[/img][/url]';   
1721                                 }
1722                                 else {
1723                                         if(isset($entry->picture))
1724                                                 $datarray['body'] .= "\n" . '[img]' . $entry->picture . '[/img]';
1725                                         // if just a link, it may be a wall photo - check
1726                                         if(isset($entry->link))
1727                                                 $datarray['body'] .= fb_get_photo($uid,$entry->link);
1728                                 }
1729                         }
1730
1731                         if (($datarray['app'] == "Events") and isset($entry->actions))
1732                                 foreach ($entry->actions as $action)
1733                                         if ($action->name == "View")
1734                                                 $datarray['body'] .= " [url=".$action->link."]".$entry->story."[/url]";
1735
1736                         // Just as a test - to see if these are the missing entries
1737                         //if(trim($datarray['body']) == '')
1738                         //      $datarray['body'] = $entry->story;
1739
1740                         // Adding the "story" text to see if there are useful data in it (testing)
1741                         //if (($datarray['app'] != "Events") and $entry->story)
1742                         //      $datarray['body'] .= "\n".$entry->story;
1743
1744                         if(trim($datarray['body']) == '') {
1745                                 logger('facebook: empty body '.$entry->id.' '.print_r($entry, true));
1746                                 continue;
1747                         }
1748
1749                         $datarray['body'] .= "\n";
1750
1751                         if (isset($entry->icon))
1752                                 $datarray['body'] .= "[img]".$entry->icon."[/img] &nbsp; ";
1753
1754                         if (isset($entry->actions))
1755                                 foreach ($entry->actions as $action)
1756                                         if (($action->name != "Comment") and ($action->name != "Like"))
1757                                                 $datarray['body'] .= "[url=".$action->link."]".$action->name."[/url] &nbsp; ";
1758
1759                         $datarray['body'] = trim($datarray['body']);
1760
1761                         //if(($datarray['body'] != '') and ($uid == 1))
1762                         //      $datarray['body'] .= "[noparse]".print_r($entry, true)."[/noparse]";
1763
1764             if (isset($entry->place)) {
1765                             if ($entry->place->name or $entry->place->location->street or
1766                                     $entry->place->location->city or $entry->place->location->Denmark) {
1767                                     $datarray['coord'] = '';
1768                                     if ($entry->place->name)
1769                                             $datarray['coord'] .= $entry->place->name;
1770                                     if ($entry->place->location->street)
1771                                             $datarray['coord'] .= $entry->place->location->street;
1772                                     if ($entry->place->location->city)
1773                                             $datarray['coord'] .= " ".$entry->place->location->city;
1774                                     if ($entry->place->location->country)
1775                                             $datarray['coord'] .= " ".$entry->place->location->country;
1776                             } else if ($entry->place->location->latitude and $entry->place->location->longitude)
1777                                     $datarray['coord'] = substr($entry->place->location->latitude, 0, 8)
1778                                                         .' '.substr($entry->place->location->longitude, 0, 8);
1779             }
1780                         $datarray['created'] = datetime_convert('UTC','UTC',$entry->created_time);
1781                         $datarray['edited'] = datetime_convert('UTC','UTC',$entry->updated_time);
1782
1783                         // If the entry has a privacy policy, we cannot assume who can or cannot see it,
1784                         // as the identities are from a foreign system. Mark it as private to the owner.
1785
1786                         if(isset($entry->privacy) && $entry->privacy->value !== 'EVERYONE') {
1787                                 $datarray['private'] = 1;
1788                                 $datarray['allow_cid'] = '<' . $self[0]['id'] . '>';
1789                         }
1790
1791                         $top_item = item_store($datarray);
1792                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1793                                 intval($top_item),
1794                                 intval($uid)
1795                         );
1796                         if(count($r)) {
1797                                 $orig_post = $r[0];
1798                                 logger('fb: new top level item posted');
1799                         }
1800                 }
1801
1802                 /**  @var array $orig_post */
1803
1804         $likers_num = (isset($entry->likes) && isset($entry->likes->count) ? IntVal($entry->likes->count) : 0 );
1805                 if(isset($entry->likes) && isset($entry->likes->data))
1806                         $likers = $entry->likes->data;
1807                 else
1808                         $likers = null;
1809
1810         $comments_num = (isset($entry->comments) && isset($entry->comments->count) ? IntVal($entry->comments->count) : 0 );
1811                 if(isset($entry->comments) && isset($entry->comments->data))
1812                         $comments = $entry->comments->data;
1813                 else
1814                         $comments = null;
1815
1816         $needs_sync = false;
1817
1818         if(is_array($likers)) {
1819                         foreach($likers as $likes) fb_consume_like($a, $user, $self, $self_id, $wall, $orig_post, $likes);
1820             if ($sync_comments) {
1821                 $r = q("SELECT COUNT(*) likes FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s' AND `parent-uri` != `uri`",
1822                     dbesc($orig_post['uri']),
1823                     intval($uid),
1824                     dbesc(ACTIVITY_LIKE)
1825                 );
1826                 if ($r[0]['likes'] < $likers_num) {
1827                     logger('fb_consume_stream: missing likes found for ' . $orig_post['uri'] . ' (we have ' . $r[0]['likes'] . ' of ' . $likers_num . '). Synchronizing...', LOGGER_DEBUG);
1828                     $needs_sync = true;
1829                 }
1830             }
1831                 }
1832
1833                 if(is_array($comments)) {
1834                         foreach($comments as $cmnt) fb_consume_comment($a, $user, $self, $self_id, $wall, $orig_post, $cmnt);
1835                         if ($sync_comments) {
1836                             $r = q("SELECT COUNT(*) comments FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s' AND `parent-uri` != `uri`",
1837                     dbesc($orig_post['uri']),
1838                     intval($uid),
1839                     ACTIVITY_POST
1840                 );
1841                             if ($r[0]['comments'] < $comments_num) {
1842                     logger('fb_consume_stream: missing comments found for ' . $orig_post['uri'] . ' (we have ' . $r[0]['comments'] . ' of ' . $comments_num . '). Synchronizing...', LOGGER_DEBUG);
1843                     $needs_sync = true;
1844                 }
1845                         }
1846                 }
1847
1848                 if ($needs_sync) fb_consume_status($a, $user, $entry, $self, $self_id, $wall, $orig_post);
1849         }
1850 }
1851
1852
1853 /**
1854  * @return bool|string
1855  */
1856 function fb_get_app_access_token() {
1857         
1858         $acc_token = get_config('facebook','app_access_token');
1859         
1860         if ($acc_token !== false) return $acc_token;
1861         
1862         $appid = get_config('facebook','appid');
1863         $appsecret = get_config('facebook', 'appsecret');
1864         
1865         if ($appid === false || $appsecret === false) {
1866                 logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
1867                 return false;
1868         }
1869         logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
1870         $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
1871         
1872         if(strpos($x,'access_token=') !== false) {
1873                 logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
1874         
1875                 $token = str_replace('access_token=', '', $x);
1876                 if(strpos($token,'&') !== false)
1877                         $token = substr($token,0,strpos($token,'&'));
1878                 
1879                 if ($token == "") {
1880                         logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
1881                         return false;
1882                 }
1883                 set_config('facebook','app_access_token',$token);
1884                 return $token;
1885         } else {
1886                 logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
1887                 return false;
1888         }
1889 }
1890
1891 function facebook_subscription_del_users() {
1892         $a = get_app();
1893         $access_token = fb_get_app_access_token();
1894         
1895         $url = "https://graph.facebook.com/" . get_config('facebook', 'appid'  ) . "/subscriptions?access_token=" . $access_token;
1896         facebook_delete_url($url);
1897         
1898         if (!facebook_check_realtime_active()) del_config('facebook', 'realtime_active');
1899 }
1900
1901 /**
1902  * @param bool $second_try
1903  */
1904 function facebook_subscription_add_users($second_try = false) {
1905         $a = get_app();
1906         $access_token = fb_get_app_access_token();
1907         
1908         $url = "https://graph.facebook.com/" . get_config('facebook', 'appid'  ) . "/subscriptions?access_token=" . $access_token;
1909         
1910         list($usec, $sec) = explode(" ", microtime());
1911         $verify_token = sha1($usec . $sec . rand(0, 999999999));
1912         set_config('facebook', 'cb_verify_token', $verify_token);
1913         
1914         $cb = $a->get_baseurl() . '/facebook/?realtime_cb=1';
1915         
1916         $j = post_url($url,array(
1917                 "object" => "user",
1918                 "fields" => "feed,friends",
1919                 "callback_url" => $cb,
1920                 "verify_token" => $verify_token,
1921         ));
1922         del_config('facebook', 'cb_verify_token');
1923         
1924         if ($j) {
1925                 $x = json_decode($j);
1926                 logger("Facebook reponse: " . $j, LOGGER_DATA);
1927                 if (isset($x->error)) {
1928                         logger('facebook_subscription_add_users: got an error: ' . $j);
1929                         if ($x->error->type == "OAuthException" && $x->error->code == 190) {
1930                                 del_config('facebook', 'app_access_token');
1931                                 if ($second_try === false) facebook_subscription_add_users(true);
1932                         }
1933                 } else {
1934                         logger('facebook_subscription_add_users: sucessful');
1935                         if (facebook_check_realtime_active()) set_config('facebook', 'realtime_active', 1);
1936                 }
1937         };
1938 }
1939
1940 /**
1941  * @return null|array
1942  */
1943 function facebook_subscriptions_get() {
1944         
1945         $access_token = fb_get_app_access_token();
1946         if (!$access_token) return null;
1947         
1948         $url = "https://graph.facebook.com/" . get_config('facebook', 'appid'  ) . "/subscriptions?access_token=" . $access_token;
1949         $j = fetch_url($url);
1950         $ret = null;
1951         if ($j) {
1952                 $x = json_decode($j);
1953                 if (isset($x->data)) $ret = $x->data;
1954         }
1955         return $ret;
1956 }
1957
1958
1959 /**
1960  * @return bool
1961  */
1962 function facebook_check_realtime_active() {
1963         $ret = facebook_subscriptions_get();
1964         if (is_null($ret)) return false;
1965         if (is_array($ret)) foreach ($ret as $re) if (is_object($re) && $re->object == "user") return true;
1966         return false;
1967 }
1968
1969
1970
1971
1972 // DELETE-request to $url
1973
1974 if(! function_exists('facebook_delete_url')) {
1975     /**
1976      * @param string $url
1977      * @param null|array $headers
1978      * @param int $redirects
1979      * @param int $timeout
1980      * @return bool|string
1981      */
1982     function facebook_delete_url($url,$headers = null, &$redirects = 0, $timeout = 0) {
1983         $a = get_app();
1984         $ch = curl_init($url);
1985         if(($redirects > 8) || (! $ch)) 
1986                 return false;
1987
1988         curl_setopt($ch, CURLOPT_HEADER, true);
1989         curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
1990         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
1991         curl_setopt($ch, CURLOPT_USERAGENT, "Friendica");
1992
1993         if(intval($timeout)) {
1994                 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
1995         }
1996         else {
1997                 $curl_time = intval(get_config('system','curl_timeout'));
1998                 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
1999         }
2000
2001         if(defined('LIGHTTPD')) {
2002                 if(!is_array($headers)) {
2003                         $headers = array('Expect:');
2004                 } else {
2005                         if(!in_array('Expect:', $headers)) {
2006                                 array_push($headers, 'Expect:');
2007                         }
2008                 }
2009         }
2010         if($headers)
2011                 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
2012
2013         $check_cert = get_config('system','verifyssl');
2014         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
2015         $prx = get_config('system','proxy');
2016         if(strlen($prx)) {
2017                 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
2018                 curl_setopt($ch, CURLOPT_PROXY, $prx);
2019                 $prxusr = get_config('system','proxyuser');
2020                 if(strlen($prxusr))
2021                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
2022         }
2023
2024         $a->set_curl_code(0);
2025
2026         // don't let curl abort the entire application
2027         // if it throws any errors.
2028
2029         $s = @curl_exec($ch);
2030
2031         $base = $s;
2032         $curl_info = curl_getinfo($ch);
2033         $http_code = $curl_info['http_code'];
2034
2035         $header = '';
2036
2037         // Pull out multiple headers, e.g. proxy and continuation headers
2038         // allow for HTTP/2.x without fixing code
2039
2040         while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
2041                 $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
2042                 $header .= $chunk;
2043                 $base = substr($base,strlen($chunk));
2044         }
2045
2046         if($http_code == 301 || $http_code == 302 || $http_code == 303) {
2047         $matches = array();
2048         preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
2049         $url = trim(array_pop($matches));
2050         $url_parsed = @parse_url($url);
2051         if (isset($url_parsed)) {
2052             $redirects++;
2053             return facebook_delete_url($url,$headers,$redirects,$timeout);
2054         }
2055     }
2056         $a->set_curl_code($http_code);
2057         $body = substr($s,strlen($header));
2058
2059         $a->set_curl_headers($header);
2060
2061         curl_close($ch);
2062         return($body);
2063 }}