Merge pull request #46 from CatoTH/master

Several changes to Facebook-Connector
This commit is contained in:
friendica 2012-04-17 03:44:42 -07:00
commit 46f460a6ec
2 changed files with 299 additions and 235 deletions

View file

@ -1,43 +1,7 @@
Installing the Friendica/Facebook connector Installing the Friendica/Facebook connector
1. Visit https://developers.facebook.com/apps to register an app. Detailed instructions how to use this plugin can be found at
a) Click "Create a new app" https://github.com/friendica/friendica/wiki/How-to:-Friendica%E2%80%99s-Facebook-connector
b) We'd be very happy if you include "Friendica" in the application name
to increase name recognition.
c) Edit your app settings on the setup page. The Friendica icons are present
in the images directory and may be uploaded as a Facebook app icon. Use
images/friendica-16.jpg for the Icon and images/Friendica-128.jpg for the logo.
d) In the App Display name enter the name of your app (this should default to the
name you chose in part a).
e) Enter YourDomain.com in the App Domain field and hit return.
f) In "Select how your app connects with Facebook select "Website" and enter the
full URL to your Friendica install including HTTPS and a trailing slash.
2. Enable the Facebook plugin by clicking on the icon next to it's name on the plugin
page of your admin panel.
b) return to the Facebook plugin page in your admin panel, and fill in the App-ID
and Application Secret settings you got from Facebook.
c) Click save.
d) Finally, return to the Facebook settings page, and activate real-time updates.
i. If you for any reason prefer to use a configuration file instead of the admin panels,
Activate the plugin by including it in .htconfig.php, e.g.
$a->config['system']['addon'] = 'plugin1,plugin2,facebook';
and set the following values:
$a->config['facebook']['appid'] = 'xxxxxxxxxxx';
$a->config['facebook']['appsecret'] = 'xxxxxxxxxxxxxxx';
Replace with the settings Facebook gives you.
3. To use the Facebook plugin, visit the "connector settings" area of your settings
page. Click "Install Facebook Connector".
4. This will ask you to login to Facebook and allow the plugin to do it's stuff.
Allow it to do so.
5. You're done. To turn it off visit the Plugin Settings page again and
'Remove Facebook posting'.
Vidoes and embeds will not be posted if there is no other content. Links Vidoes and embeds will not be posted if there is no other content. Links
and images will be converted to a format suitable for the Facebook API and and images will be converted to a format suitable for the Facebook API and

296
facebook/facebook.php Executable file → Normal file
View file

@ -1,7 +1,7 @@
<?php <?php
/** /**
* Name: Facebook Connector * Name: Facebook Connector
* Version: 1.1 * Version: 1.2
* Author: Mike Macgirvin <http://macgirvin.com/profile/mike> * Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
* Tobias Hößl <https://github.com/CatoTH/> * Tobias Hößl <https://github.com/CatoTH/>
*/ */
@ -9,33 +9,8 @@
/** /**
* Installing the Friendica/Facebook connector * Installing the Friendica/Facebook connector
* *
* 1. register an API key for your site from developer.facebook.com * Detailed instructions how to use this plugin can be found at
* a. We'd be very happy if you include "Friendica" in the application name * https://github.com/friendica/friendica/wiki/How-to:-Friendica%E2%80%99s-Facebook-connector
* to increase name recognition. The Friendica icons are also present
* in the images directory and may be uploaded as a Facebook app icon.
* Use images/friendica-16.jpg for the Icon and images/friendica-128.jpg for the Logo.
* b. The url should be your site URL with a trailing slash.
* Friendica is a software application and does not require a Privacy Policy
* or Terms of Service, though your installation of it might. Facebook may require
* that you provide a Privacy Policy, which we find ironic.
* c. Set the following values in your .htconfig.php file
* $a->config['facebook']['appid'] = 'xxxxxxxxxxx';
* $a->config['facebook']['appsecret'] = 'xxxxxxxxxxxxxxx';
* Replace with the settings Facebook gives you.
* d. Navigate to Set Web->Site URL & Domain -> Website Settings. Set
* Site URL to yoursubdomain.yourdomain.com. Set Site Domain to your
* yourdomain.com.
* 2. Visit the Facebook Settings section of the "Settings->Plugin Settings" page.
* and click 'Install Facebook Connector'.
* 3. Visit the Facebook Settings section of the "Settings->Plugin Settings" page.
* and click 'Install Facebook Connector'.
* 4. This will ask you to login to Facebook and grant permission to the
* plugin to do its stuff. Allow it to do so.
* 5. Optional step: If you want to use Facebook Real Time Updates (so new messages
* and new contacts are added ~1min after they are postet / added on FB), go to
* Settings -> plugins -> facebook and press the "Activate Real-Time Updates"-button.
* 6. You're done. To turn it off visit the Plugin Settings page again and
* 'Remove Facebook posting'.
* *
* Vidoes and embeds will not be posted if there is no other content. Links * Vidoes and embeds will not be posted if there is no other content. Links
* and images will be converted to a format suitable for the Facebook API and * and images will be converted to a format suitable for the Facebook API and
@ -96,6 +71,9 @@ function facebook_module() {}
// If a->argv[1] is a nickname, this is a callback from Facebook oauth requests. // If a->argv[1] is a nickname, this is a callback from Facebook oauth requests.
// If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API // If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API
/**
* @param App $a
*/
function facebook_init(&$a) { function facebook_init(&$a) {
if (x($_REQUEST, "realtime_cb") && x($_REQUEST, "realtime_cb")) { if (x($_REQUEST, "realtime_cb") && x($_REQUEST, "realtime_cb")) {
@ -191,7 +169,7 @@ function facebook_init(&$a) {
$r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1", $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
dbesc($nick) dbesc($nick)
); );
if(! count($r)) if(!(isset($r) && count($r)))
return; return;
$uid = $r[0]['uid']; $uid = $r[0]['uid'];
@ -233,6 +211,9 @@ function facebook_init(&$a) {
} }
/**
* @param int $uid
*/
function fb_get_self($uid) { function fb_get_self($uid) {
$access_token = get_pconfig($uid,'facebook','access_token'); $access_token = get_pconfig($uid,'facebook','access_token');
if(! $access_token) if(! $access_token)
@ -244,7 +225,14 @@ function fb_get_self($uid) {
} }
} }
function fb_get_friends_sync_new($uid, $access_token, $person) { /**
* @param int $uid
* @param string $access_token
* @param array $persons
*/
function fb_get_friends_sync_new($uid, $access_token, $persons) {
$persons_todo = array();
foreach ($persons as $person) {
$link = 'http://facebook.com/profile.php?id=' . $person->id; $link = 'http://facebook.com/profile.php?id=' . $person->id;
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
@ -254,30 +242,29 @@ function fb_get_friends_sync_new($uid, $access_token, $person) {
if (count($r) == 0) { if (count($r) == 0) {
logger('fb_get_friends: new contact found: ' . $link, LOGGER_DEBUG); logger('fb_get_friends: new contact found: ' . $link, LOGGER_DEBUG);
$persons_todo[] = $person;
}
fb_get_friends_sync_full($uid, $access_token, $person); if (count($persons_todo) > 0) fb_get_friends_sync_full($uid, $access_token, $persons_todo);
} }
} }
function fb_get_friends_sync_full($uid, $access_token, $person) { /**
$s = fetch_url('https://graph.facebook.com/' . $person->id . '?access_token=' . $access_token); * @param int $uid
if($s) { * @param object $contact
$jp = json_decode($s); */
logger('fb_get_friends: info: ' . print_r($jp,true), LOGGER_DATA); function fb_get_friends_sync_parsecontact($uid, $contact) {
$contact->link = 'http://facebook.com/profile.php?id=' . $contact->id;
// always use numeric link for consistency
$jp->link = 'http://facebook.com/profile.php?id=' . $person->id;
// If its a page then set the first name from the username // If its a page then set the first name from the username
if (!$jp->first_name and $jp->username) if (!$contact->first_name and $contact->username)
$jp->first_name = $jp->username; $contact->first_name = $contact->username;
// check if we already have a contact // check if we already have a contact
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
intval($uid), intval($uid),
dbesc($jp->link) dbesc($contact->link)
); );
if(count($r)) { if(count($r)) {
@ -287,9 +274,9 @@ function fb_get_friends_sync_full($uid, $access_token, $person) {
if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro'])) { if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro'])) {
require_once("Photo.php"); require_once("Photo.php");
$photos = import_profile_photo('https://graph.facebook.com/' . $jp->id . '/picture', $uid, $r[0]['id']); $photos = import_profile_photo('https://graph.facebook.com/' . $contact->id . '/picture', $uid, $r[0]['id']);
$r = q("UPDATE `contact` SET `photo` = '%s', q("UPDATE `contact` SET `photo` = '%s',
`thumb` = '%s', `thumb` = '%s',
`micro` = '%s', `micro` = '%s',
`name-date` = '%s', `name-date` = '%s',
@ -311,21 +298,21 @@ function fb_get_friends_sync_full($uid, $access_token, $person) {
else { else {
// create contact record // create contact record
$r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`, q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
`name`, `nick`, `photo`, `network`, `rel`, `priority`, `name`, `nick`, `photo`, `network`, `rel`, `priority`,
`writable`, `blocked`, `readonly`, `pending` ) `writable`, `blocked`, `readonly`, `pending` )
VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ", VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
intval($uid), intval($uid),
dbesc(datetime_convert()), dbesc(datetime_convert()),
dbesc($jp->link), dbesc($contact->link),
dbesc(normalise_link($jp->link)), dbesc(normalise_link($contact->link)),
dbesc(''), dbesc(''),
dbesc(''), dbesc(''),
dbesc($jp->id), dbesc($contact->id),
dbesc('facebook ' . $jp->id), dbesc('facebook ' . $contact->id),
dbesc($jp->name), dbesc($contact->name),
dbesc(($jp->nickname) ? $jp->nickname : strtolower($jp->first_name)), dbesc(($contact->nickname) ? $contact->nickname : strtolower($contact->first_name)),
dbesc('https://graph.facebook.com/' . $jp->id . '/picture'), dbesc('https://graph.facebook.com/' . $contact->id . '/picture'),
dbesc(NETWORK_FACEBOOK), dbesc(NETWORK_FACEBOOK),
intval(CONTACT_IS_FRIEND), intval(CONTACT_IS_FRIEND),
intval(1), intval(1),
@ -334,7 +321,7 @@ function fb_get_friends_sync_full($uid, $access_token, $person) {
} }
$r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
dbesc($jp->link), dbesc($contact->link),
intval($uid) intval($uid)
); );
@ -342,14 +329,13 @@ function fb_get_friends_sync_full($uid, $access_token, $person) {
return; return;
} }
$contact = $r[0];
$contact_id = $r[0]['id']; $contact_id = $r[0]['id'];
require_once("Photo.php"); require_once("Photo.php");
$photos = import_profile_photo($r[0]['photo'],$uid,$contact_id); $photos = import_profile_photo($r[0]['photo'],$uid,$contact_id);
$r = q("UPDATE `contact` SET `photo` = '%s', q("UPDATE `contact` SET `photo` = '%s',
`thumb` = '%s', `thumb` = '%s',
`micro` = '%s', `micro` = '%s',
`name-date` = '%s', `name-date` = '%s',
@ -365,12 +351,39 @@ function fb_get_friends_sync_full($uid, $access_token, $person) {
dbesc(datetime_convert()), dbesc(datetime_convert()),
intval($contact_id) intval($contact_id)
); );
}
/**
* @param int $uid
* @param string $access_token
* @param array $persons
*/
function fb_get_friends_sync_full($uid, $access_token, $persons) {
if (count($persons) == 0) return;
$nums = Ceil(count($persons) / 50);
for ($i = 0; $i < $nums; $i++) {
$batch_request = array();
for ($j = $i * 50; $j < ($i+1) * 50 && $j < count($persons); $j++) $batch_request[] = array('method'=>'GET', 'relative_url'=>$persons[$j]->id);
$s = post_url('https://graph.facebook.com/', array('access_token' => $access_token, 'batch' => json_encode($batch_request)));
if($s) {
$results = json_decode($s);
logger('fb_get_friends: info: ' . print_r($results,true), LOGGER_DATA);
foreach ($results as $contact) {
if ($contact->code != 200) logger('fb_get_friends: not found: ' . print_r($contact,true), LOGGER_DEBUG);
else fb_get_friends_sync_parsecontact($uid, json_decode($contact->body));
} }
} }
}
}
// if $fullsync is true, only new contacts are searched for // if $fullsync is true, only new contacts are searched for
/**
* @param int $uid
* @param bool $fullsync
*/
function fb_get_friends($uid, $fullsync = true) { function fb_get_friends($uid, $fullsync = true) {
$r = q("SELECT `uid` FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1", $r = q("SELECT `uid` FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
@ -394,17 +407,23 @@ function fb_get_friends($uid, $fullsync = true) {
logger('facebook: fb_get_friends: json: ' . print_r($j,true), LOGGER_DATA); logger('facebook: fb_get_friends: json: ' . print_r($j,true), LOGGER_DATA);
if(! $j->data) if(! $j->data)
return; return;
foreach($j->data as $person)
$persons_todo = array();
foreach($j->data as $person) $persons_todo[] = $person;
if ($fullsync) if ($fullsync)
fb_get_friends_sync_full($uid, $access_token, $person); fb_get_friends_sync_full($uid, $access_token, $persons_todo);
else else
fb_get_friends_sync_new($uid, $access_token, $person); fb_get_friends_sync_new($uid, $access_token, $persons_todo);
} }
} }
// This is the POST method to the facebook settings page // This is the POST method to the facebook settings page
// Content is posted to Facebook in the function facebook_post_hook() // Content is posted to Facebook in the function facebook_post_hook()
/**
* @param App $a
*/
function facebook_post(&$a) { function facebook_post(&$a) {
$uid = local_user(); $uid = local_user();
@ -455,6 +474,10 @@ function facebook_post(&$a) {
// Facebook settings form // Facebook settings form
/**
* @param App $a
* @return string
*/
function facebook_content(&$a) { function facebook_content(&$a) {
if(! local_user()) { if(! local_user()) {
@ -478,7 +501,6 @@ function facebook_content(&$a) {
if (get_pconfig(local_user(),'facebook','post')) { if (get_pconfig(local_user(),'facebook','post')) {
$access_token = get_pconfig(local_user(),'facebook','access_token'); $access_token = get_pconfig(local_user(),'facebook','access_token');
if ($access_token) { if ($access_token) {
$private_wall = intval(get_pconfig($uid,'facebook','private_wall'));
$s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token); $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
if($s) { if($s) {
$j = json_decode($s); $j = json_decode($s);
@ -556,11 +578,12 @@ function facebook_content(&$a) {
} }
/**
* @param App $a
* @param null|object $b
* @return mixed
*/
function facebook_cron($a,$b) { function facebook_cron($a,$b) {
//del_config('facebook', 'realtime_active');
//del_config('facebook', 'realtime_err_mailsent');
//del_config('facebook', 'cb_verify_token');
$last = get_config('facebook','last_poll'); $last = get_config('facebook','last_poll');
@ -600,6 +623,8 @@ function facebook_cron($a,$b) {
$last_friend_check = get_pconfig($rr['uid'],'facebook','friend_check'); $last_friend_check = get_pconfig($rr['uid'],'facebook','friend_check');
if($last_friend_check) if($last_friend_check)
$next_friend_check = $last_friend_check + 86400; $next_friend_check = $last_friend_check + 86400;
else
$next_friend_check = 0;
if($next_friend_check <= time()) { if($next_friend_check <= time()) {
fb_get_friends($rr['uid'], true); fb_get_friends($rr['uid'], true);
set_pconfig($rr['uid'],'facebook','friend_check',time()); set_pconfig($rr['uid'],'facebook','friend_check',time());
@ -620,7 +645,7 @@ function facebook_cron($a,$b) {
logger('facebook_cron: Failed', LOGGER_NORMAL); logger('facebook_cron: Failed', LOGGER_NORMAL);
if(strlen($a->config['admin_email']) && !get_config('facebook', 'realtime_err_mailsent')) { if(strlen($a->config['admin_email']) && !get_config('facebook', 'realtime_err_mailsent')) {
$res = mail($a->config['admin_email'], t('Problems with Facebook Real-Time Updates'), mail($a->config['admin_email'], t('Problems with Facebook Real-Time Updates'),
"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.", "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.",
'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n" 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
. 'Content-type: text/plain; charset=UTF-8' . "\n" . 'Content-type: text/plain; charset=UTF-8' . "\n"
@ -640,7 +665,10 @@ function facebook_cron($a,$b) {
} }
/**
* @param App $a
* @param null|object $b
*/
function facebook_plugin_settings(&$a,&$b) { function facebook_plugin_settings(&$a,&$b) {
$b .= '<div class="settings-block">'; $b .= '<div class="settings-block">';
@ -651,6 +679,10 @@ function facebook_plugin_settings(&$a,&$b) {
} }
/**
* @param App $a
* @param null|object $o
*/
function facebook_plugin_admin(&$a, &$o){ function facebook_plugin_admin(&$a, &$o){
@ -695,7 +727,11 @@ function facebook_plugin_admin(&$a, &$o){
} }
} }
function facebook_plugin_admin_post(&$a){ /**
* @param App $a
* @param null|object $o
*/
function facebook_plugin_admin_post(&$a, &$o){
check_form_security_token_redirectOnErr('/admin/plugins/facebook', 'fbsave'); check_form_security_token_redirectOnErr('/admin/plugins/facebook', 'fbsave');
if (x($_REQUEST,'fb_save_keys')) { if (x($_REQUEST,'fb_save_keys')) {
@ -714,6 +750,11 @@ function facebook_plugin_admin_post(&$a){
} }
} }
/**
* @param App $a
* @param object $b
* @return mixed
*/
function facebook_jot_nets(&$a,&$b) { function facebook_jot_nets(&$a,&$b) {
if(! local_user()) if(! local_user())
return; return;
@ -728,6 +769,11 @@ function facebook_jot_nets(&$a,&$b) {
} }
/**
* @param App $a
* @param object $b
* @return mixed
*/
function facebook_post_hook(&$a,&$b) { function facebook_post_hook(&$a,&$b) {
@ -746,6 +792,9 @@ function facebook_post_hook(&$a,&$b) {
$reply = false; $reply = false;
$likes = false; $likes = false;
$deny_arr = array();
$allow_arr = array();
$toplevel = (($b['id'] == $b['parent']) ? true : false); $toplevel = (($b['id'] == $b['parent']) ? true : false);
@ -792,7 +841,6 @@ function facebook_post_hook(&$a,&$b) {
$allow_str = dbesc(implode(', ',$recipients)); $allow_str = dbesc(implode(', ',$recipients));
if($allow_str) { if($allow_str) {
$r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'"); $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
$allow_arr = array();
if(count($r)) if(count($r))
foreach($r as $rr) foreach($r as $rr)
$allow_arr[] = $rr['notify']; $allow_arr[] = $rr['notify'];
@ -801,7 +849,6 @@ function facebook_post_hook(&$a,&$b) {
$deny_str = dbesc(implode(', ',$deny)); $deny_str = dbesc(implode(', ',$deny));
if($deny_str) { if($deny_str) {
$r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'"); $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
$deny_arr = array();
if(count($r)) if(count($r))
foreach($r as $rr) foreach($r as $rr)
$deny_arr[] = $rr['notify']; $deny_arr[] = $rr['notify'];
@ -857,8 +904,8 @@ function facebook_post_hook(&$a,&$b) {
// unless it's a dislike - just send the text as a comment // unless it's a dislike - just send the text as a comment
if($b['verb'] == ACTIVITY_DISLIKE) // if($b['verb'] == ACTIVITY_DISLIKE)
$msg = trim(strip_tags(bbcode($msg))); // $msg = trim(strip_tags(bbcode($msg)));
// Old code // Old code
/*$search_str = $a->get_baseurl() . '/search'; /*$search_str = $a->get_baseurl() . '/search';
@ -968,7 +1015,6 @@ function facebook_post_hook(&$a,&$b) {
// Since facebook increased the maxpostlen massively this never should happen again :) // Since facebook increased the maxpostlen massively this never should happen again :)
if (strlen($msg) > FACEBOOK_MAXPOSTLEN) { if (strlen($msg) > FACEBOOK_MAXPOSTLEN) {
$shortlink = "";
require_once('library/slinky.php'); require_once('library/slinky.php');
$display_url = $b['plink']; $display_url = $b['plink'];
@ -1102,6 +1148,10 @@ function facebook_post_hook(&$a,&$b) {
} }
} }
/**
* @param App $app
* @param object $data
*/
function facebook_enotify(&$app, &$data) { function facebook_enotify(&$app, &$data) {
if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') { if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
$data['itemlink'] = '/facebook'; $data['itemlink'] = '/facebook';
@ -1111,6 +1161,10 @@ function facebook_enotify(&$app, &$data) {
} }
} }
/**
* @param App $a
* @param object $b
*/
function facebook_post_local(&$a,&$b) { function facebook_post_local(&$a,&$b) {
// Figure out if Facebook posting is enabled for this post and file it in 'postopts' // Figure out if Facebook posting is enabled for this post and file it in 'postopts'
@ -1137,6 +1191,10 @@ function facebook_post_local(&$a,&$b) {
} }
/**
* @param App $a
* @param object $b
*/
function fb_queue_hook(&$a,&$b) { function fb_queue_hook(&$a,&$b) {
$qi = q("SELECT * FROM `queue` WHERE `network` = '%s'", $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
@ -1195,8 +1253,14 @@ function fb_queue_hook(&$a,&$b) {
} }
} }
/**
* @param string $access_token
* @param int $since
* @return object
*/
function fb_get_timeline($access_token, &$since) { function fb_get_timeline($access_token, &$since) {
$entries = new stdClass();
$entries->data = array(); $entries->data = array();
$newest = 0; $newest = 0;
@ -1235,6 +1299,9 @@ function fb_get_timeline($access_token, &$since) {
return($entries); return($entries);
} }
/**
* @param int $uid
*/
function fb_consume_all($uid) { function fb_consume_all($uid) {
require_once('include/items.php'); require_once('include/items.php');
@ -1259,7 +1326,7 @@ function fb_consume_all($uid) {
// Get the last date // Get the last date
$lastdate = get_pconfig($uid,'facebook','lastdate'); $lastdate = get_pconfig($uid,'facebook','lastdate');
// fetch all items since the last date // fetch all items since the last date
$j = fb_get_timeline($access_token, &$lastdate); $j = fb_get_timeline($access_token, $lastdate);
if (isset($j->data)) { if (isset($j->data)) {
logger('fb_consume_stream: feed: ' . print_r($j,true), LOGGER_DATA); logger('fb_consume_stream: feed: ' . print_r($j,true), LOGGER_DATA);
fb_consume_stream($uid,$j,false); fb_consume_stream($uid,$j,false);
@ -1270,6 +1337,11 @@ function fb_consume_all($uid) {
logger('fb_consume_stream: feed: got no data from Facebook: ' . print_r($j,true), LOGGER_NORMAL); logger('fb_consume_stream: feed: got no data from Facebook: ' . print_r($j,true), LOGGER_NORMAL);
} }
/**
* @param int $uid
* @param string $link
* @return string
*/
function fb_get_photo($uid,$link) { function fb_get_photo($uid,$link) {
$access_token = get_pconfig($uid,'facebook','access_token'); $access_token = get_pconfig($uid,'facebook','access_token');
if(! $access_token || (! stristr($link,'facebook.com/photo.php'))) if(! $access_token || (! stristr($link,'facebook.com/photo.php')))
@ -1278,14 +1350,22 @@ function fb_get_photo($uid,$link) {
$ret = preg_match('/fbid=([0-9]*)/',$link,$match); $ret = preg_match('/fbid=([0-9]*)/',$link,$match);
if($ret) if($ret)
$photo_id = $match[1]; $photo_id = $match[1];
else
return "";
$x = fetch_url('https://graph.facebook.com/' . $photo_id . '?access_token=' . $access_token); $x = fetch_url('https://graph.facebook.com/' . $photo_id . '?access_token=' . $access_token);
$j = json_decode($x); $j = json_decode($x);
if($j->picture) if($j->picture)
return "\n\n" . '[url=' . $link . '][img]' . $j->picture . '[/img][/url]'; return "\n\n" . '[url=' . $link . '][img]' . $j->picture . '[/img][/url]';
//else //else
// return "\n" . '[url=' . $link . ']' . t('link') . '[/url]'; // return "\n" . '[url=' . $link . ']' . t('link') . '[/url]';
return "";
} }
/**
* @param int $uid
* @param object $j
* @param bool $wall
*/
function fb_consume_stream($uid,$j,$wall = false) { function fb_consume_stream($uid,$j,$wall = false) {
$a = get_app(); $a = get_app();
@ -1297,7 +1377,7 @@ function fb_consume_stream($uid,$j,$wall = false) {
if(! count($user)) if(! count($user))
return; return;
$my_local_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname']; // $my_local_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
$no_linking = get_pconfig($uid,'facebook','no_linking'); $no_linking = get_pconfig($uid,'facebook','no_linking');
if($no_linking) if($no_linking)
@ -1314,6 +1394,8 @@ function fb_consume_stream($uid,$j,$wall = false) {
if(! count($j->data) || (! strlen($self_id))) if(! count($j->data) || (! strlen($self_id)))
return; return;
$top_item = 0;
foreach($j->data as $entry) { foreach($j->data as $entry) {
logger('fb_consume: entry: ' . print_r($entry,true), LOGGER_DATA); logger('fb_consume: entry: ' . print_r($entry,true), LOGGER_DATA);
$datarray = array(); $datarray = array();
@ -1324,12 +1406,10 @@ function fb_consume_stream($uid,$j,$wall = false) {
intval($uid) intval($uid)
); );
if(count($r)) { if(count($r)) {
$post_exists = true;
$orig_post = $r[0]; $orig_post = $r[0];
$top_item = $r[0]['id']; $top_item = $r[0]['id'];
} }
else { else {
$post_exists = false;
$orig_post = null; $orig_post = null;
} }
@ -1393,32 +1473,32 @@ function fb_consume_stream($uid,$j,$wall = false) {
logger('facebook: post '.$entry->id.' from '.$from->name); logger('facebook: post '.$entry->id.' from '.$from->name);
$datarray['body'] = escape_tags($entry->message); $datarray['body'] = (x($entry, 'message') ? escape_tags($entry->message) : '');
if($entry->name and $entry->link) if(x($entry, 'name') and x($entry, 'link'))
$datarray['body'] .= "\n\n[bookmark=".$entry->link."]".$entry->name."[/bookmark]"; $datarray['body'] .= "\n\n[bookmark=".$entry->link."]".$entry->name."[/bookmark]";
elseif ($entry->name) elseif (x($entry, 'name'))
$datarray['body'] .= "\n\n[b]" . $entry->name."[/b]"; $datarray['body'] .= "\n\n[b]" . $entry->name."[/b]";
if($entry->caption) { if(x($entry, 'caption')) {
if(!$entry->name and $entry->link) if(!x($entry, 'name') and x($entry, 'link'))
$datarray['body'] .= "\n\n[bookmark=".$entry->link."]".$entry->caption."[/bookmark]"; $datarray['body'] .= "\n\n[bookmark=".$entry->link."]".$entry->caption."[/bookmark]";
else else
$datarray['body'] .= "[i]" . $entry->caption."[/i]\n"; $datarray['body'] .= "[i]" . $entry->caption."[/i]\n";
} }
if(!$entry->caption and !$entry->name) { if(!x($entry, 'caption') and !x($entry, 'name')) {
if ($entry->link) if (x($entry, 'link'))
$datarray['body'] .= "\n[url]".$entry->link."[/url]\n"; $datarray['body'] .= "\n[url]".$entry->link."[/url]\n";
else else
$datarray['body'] .= "\n"; $datarray['body'] .= "\n";
} }
$quote = ""; $quote = "";
if($entry->description) if(x($entry, 'description'))
$quote = $entry->description; $quote = $entry->description;
if ($entry->properties) if (x($entry, 'properties'))
foreach ($entry->properties as $property) foreach ($entry->properties as $property)
$quote .= "\n".$property->name.": [url=".$property->href."]".$property->text."[/url]"; $quote .= "\n".$property->name.": [url=".$property->href."]".$property->text."[/url]";
@ -1428,19 +1508,19 @@ function fb_consume_stream($uid,$j,$wall = false) {
// Only import the picture when the message is no video // Only import the picture when the message is no video
// oembed display a picture of the video as well // oembed display a picture of the video as well
if ($entry->type != "video") { if ($entry->type != "video") {
if($entry->picture && $entry->link) { if(x($entry, 'picture') && x($entry, 'link')) {
$datarray['body'] .= "\n" . '[url=' . $entry->link . '][img]'.$entry->picture.'[/img][/url]'; $datarray['body'] .= "\n" . '[url=' . $entry->link . '][img]'.$entry->picture.'[/img][/url]';
} }
else { else {
if($entry->picture) if(x($entry, 'picture'))
$datarray['body'] .= "\n" . '[img]' . $entry->picture . '[/img]'; $datarray['body'] .= "\n" . '[img]' . $entry->picture . '[/img]';
// if just a link, it may be a wall photo - check // if just a link, it may be a wall photo - check
if($entry->link) if(x($entry, 'link'))
$datarray['body'] .= fb_get_photo($uid,$entry->link); $datarray['body'] .= fb_get_photo($uid,$entry->link);
} }
} }
if (($datarray['app'] == "Events") and $entry->actions) if (($datarray['app'] == "Events") and x($entry, 'actions'))
foreach ($entry->actions as $action) foreach ($entry->actions as $action)
if ($action->name == "View") if ($action->name == "View")
$datarray['body'] .= " [url=".$action->link."]".$entry->story."[/url]"; $datarray['body'] .= " [url=".$action->link."]".$entry->story."[/url]";
@ -1460,10 +1540,10 @@ function fb_consume_stream($uid,$j,$wall = false) {
$datarray['body'] .= "\n"; $datarray['body'] .= "\n";
if ($entry->icon) if (x($entry, 'icon'))
$datarray['body'] .= "[img]".$entry->icon."[/img] &nbsp; "; $datarray['body'] .= "[img]".$entry->icon."[/img] &nbsp; ";
if ($entry->actions) if (x($entry, 'actions'))
foreach ($entry->actions as $action) foreach ($entry->actions as $action)
if (($action->name != "Comment") and ($action->name != "Like")) if (($action->name != "Comment") and ($action->name != "Like"))
$datarray['body'] .= "[url=".$action->link."]".$action->name."[/url] &nbsp; "; $datarray['body'] .= "[url=".$action->link."]".$action->name."[/url] &nbsp; ";
@ -1473,6 +1553,7 @@ function fb_consume_stream($uid,$j,$wall = false) {
//if(($datarray['body'] != '') and ($uid == 1)) //if(($datarray['body'] != '') and ($uid == 1))
// $datarray['body'] .= "[noparse]".print_r($entry, true)."[/noparse]"; // $datarray['body'] .= "[noparse]".print_r($entry, true)."[/noparse]";
if (x($entry, 'place')) {
if ($entry->place->name or $entry->place->location->street or if ($entry->place->name or $entry->place->location->street or
$entry->place->location->city or $entry->place->location->Denmark) { $entry->place->location->city or $entry->place->location->Denmark) {
$datarray['coord'] = ''; $datarray['coord'] = '';
@ -1487,14 +1568,14 @@ function fb_consume_stream($uid,$j,$wall = false) {
} else if ($entry->place->location->latitude and $entry->place->location->longitude) } else if ($entry->place->location->latitude and $entry->place->location->longitude)
$datarray['coord'] = substr($entry->place->location->latitude, 0, 8) $datarray['coord'] = substr($entry->place->location->latitude, 0, 8)
.' '.substr($entry->place->location->longitude, 0, 8); .' '.substr($entry->place->location->longitude, 0, 8);
}
$datarray['created'] = datetime_convert('UTC','UTC',$entry->created_time); $datarray['created'] = datetime_convert('UTC','UTC',$entry->created_time);
$datarray['edited'] = datetime_convert('UTC','UTC',$entry->updated_time); $datarray['edited'] = datetime_convert('UTC','UTC',$entry->updated_time);
// If the entry has a privacy policy, we cannot assume who can or cannot see it, // If the entry has a privacy policy, we cannot assume who can or cannot see it,
// as the identities are from a foreign system. Mark it as private to the owner. // as the identities are from a foreign system. Mark it as private to the owner.
if($entry->privacy && $entry->privacy->value !== 'EVERYONE') { if(x($entry, 'privacy') && $entry->privacy->value !== 'EVERYONE') {
$datarray['private'] = 1; $datarray['private'] = 1;
$datarray['allow_cid'] = '<' . $self[0]['id'] . '>'; $datarray['allow_cid'] = '<' . $self[0]['id'] . '>';
} }
@ -1510,12 +1591,12 @@ function fb_consume_stream($uid,$j,$wall = false) {
} }
} }
if(isset($entry->likes) && isset($entry->likes->data)) if(x($entry, 'likes') && x($entry->likes, 'data'))
$likers = $entry->likes->data; $likers = $entry->likes->data;
else else
$likers = null; $likers = null;
if(isset($entry->comments) && isset($entry->comments->data)) if(x($entry, 'comments') && x($entry->comments, 'data'))
$comments = $entry->comments->data; $comments = $entry->comments->data;
else else
$comments = null; $comments = null;
@ -1579,7 +1660,7 @@ function fb_consume_stream($uid,$j,$wall = false) {
$likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' . $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
'<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>'; '<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>';
$item = item_store($likedata); item_store($likedata);
} }
} }
if(is_array($comments)) { if(is_array($comments)) {
@ -1658,7 +1739,7 @@ function fb_consume_stream($uid,$j,$wall = false) {
'to_email' => $user[0]['email'], 'to_email' => $user[0]['email'],
'uid' => $user[0]['uid'], 'uid' => $user[0]['uid'],
'item' => $cmntdata, 'item' => $cmntdata,
'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $item, 'link' => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
'source_name' => $cmntdata['author-name'], 'source_name' => $cmntdata['author-name'],
'source_link' => $cmntdata['author-link'], 'source_link' => $cmntdata['author-link'],
'source_photo' => $cmntdata['author-avatar'], 'source_photo' => $cmntdata['author-avatar'],
@ -1677,6 +1758,9 @@ function fb_consume_stream($uid,$j,$wall = false) {
} }
/**
* @return bool|string
*/
function fb_get_app_access_token() { function fb_get_app_access_token() {
$acc_token = get_config('facebook','app_access_token'); $acc_token = get_config('facebook','app_access_token');
@ -1722,6 +1806,9 @@ function facebook_subscription_del_users() {
if (!facebook_check_realtime_active()) del_config('facebook', 'realtime_active'); if (!facebook_check_realtime_active()) del_config('facebook', 'realtime_active');
} }
/**
* @param bool $second_try
*/
function facebook_subscription_add_users($second_try = false) { function facebook_subscription_add_users($second_try = false) {
$a = get_app(); $a = get_app();
$access_token = fb_get_app_access_token(); $access_token = fb_get_app_access_token();
@ -1758,6 +1845,9 @@ function facebook_subscription_add_users($second_try = false) {
}; };
} }
/**
* @return null|array
*/
function facebook_subscriptions_get() { function facebook_subscriptions_get() {
$access_token = fb_get_app_access_token(); $access_token = fb_get_app_access_token();
@ -1774,6 +1864,9 @@ function facebook_subscriptions_get() {
} }
/**
* @return bool
*/
function facebook_check_realtime_active() { function facebook_check_realtime_active() {
$ret = facebook_subscriptions_get(); $ret = facebook_subscriptions_get();
if (is_null($ret)) return false; if (is_null($ret)) return false;
@ -1787,6 +1880,13 @@ function facebook_check_realtime_active() {
// DELETE-request to $url // DELETE-request to $url
if(! function_exists('facebook_delete_url')) { if(! function_exists('facebook_delete_url')) {
/**
* @param string $url
* @param null|array $headers
* @param int $redirects
* @param int $timeout
* @return bool|string
*/
function facebook_delete_url($url,$headers = null, &$redirects = 0, $timeout = 0) { function facebook_delete_url($url,$headers = null, &$redirects = 0, $timeout = 0) {
$a = get_app(); $a = get_app();
$ch = curl_init($url); $ch = curl_init($url);
@ -1858,7 +1958,7 @@ function facebook_delete_url($url,$headers = null, &$redirects = 0, $timeout = 0
$url_parsed = @parse_url($url); $url_parsed = @parse_url($url);
if (isset($url_parsed)) { if (isset($url_parsed)) {
$redirects++; $redirects++;
return delete_url($url,$headers,$redirects,$timeout); return facebook_delete_url($url,$headers,$redirects,$timeout);
} }
} }
$a->set_curl_code($http_code); $a->set_curl_code($http_code);