Merge develop into 1901_autocomplete

This commit is contained in:
rabuzarus 2016-01-30 16:57:54 +01:00
commit 162f754e2d
60 changed files with 4311 additions and 4280 deletions

View file

@ -132,8 +132,8 @@ function terminate_friendship($user,$self,$contact) {
diaspora_unshare($user,$contact);
}
elseif($contact['network'] === NETWORK_DFRN) {
require_once('include/items.php');
dfrn_deliver($user,$contact,'placeholder', 1);
require_once('include/dfrn.php');
dfrn::deliver($user,$contact,'placeholder', 1);
}
}
@ -208,15 +208,15 @@ function get_contact_details_by_url($url, $uid = -1) {
}
// Fetching further contact data from the contact table
$r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `network` = '%s'",
$r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd`, `self` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `network` IN ('%s', '')",
dbesc(normalise_link($url)), intval($uid), dbesc($profile["network"]));
if (!count($r) AND !isset($profile))
$r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
$r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd`, `self` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
dbesc(normalise_link($url)), intval($uid));
if (!count($r) AND !isset($profile))
$r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
$r = q("SELECT `id`, `uid`, `url`, `network`, `name`, `nick`, `addr`, `location`, `about`, `keywords`, `gender`, `photo`, `thumb`, `addr`, `forum`, `prv`, `bd` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
dbesc(normalise_link($url)));
if ($r) {
@ -228,7 +228,7 @@ function get_contact_details_by_url($url, $uid = -1) {
$profile["nick"] = $r[0]["nick"];
if (!isset($profile["addr"]) AND $r[0]["addr"])
$profile["addr"] = $r[0]["addr"];
if (!isset($profile["photo"]) AND $r[0]["photo"])
if ((!isset($profile["photo"]) OR $r[0]["self"]) AND $r[0]["photo"])
$profile["photo"] = $r[0]["photo"];
if (!isset($profile["location"]) AND $r[0]["location"])
$profile["location"] = $r[0]["location"];
@ -246,6 +246,8 @@ function get_contact_details_by_url($url, $uid = -1) {
$profile["addr"] = $r[0]["addr"];
if (!isset($profile["bd"]) AND $r[0]["bd"])
$profile["bd"] = $r[0]["bd"];
if (isset($r[0]["thumb"]))
$profile["thumb"] = $r[0]["thumb"];
if ($r[0]["uid"] == 0)
$profile["cid"] = 0;
else
@ -410,12 +412,12 @@ function get_contact($url, $uid = 0) {
return 0;
}
$contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
$contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
dbesc(normalise_link($url)),
intval($uid));
if (!$contact)
$contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `uid` = %d",
$contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `uid` = %d ORDER BY `id` LIMIT 1",
dbesc($url),
dbesc(normalise_link($url)),
intval($uid));
@ -439,9 +441,7 @@ function get_contact($url, $uid = 0) {
if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA)))
return 0;
// tempory programming. Can be deleted after 2015-02-07
if (($data["alias"] == "") AND (normalise_link($data["url"]) != normalise_link($url)))
$data["alias"] = normalise_link($url);
$url = $data["url"];
if ($contactid == 0) {
q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
@ -470,7 +470,7 @@ function get_contact($url, $uid = 0) {
dbesc($data["poco"])
);
$contact = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
$contact = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
dbesc(normalise_link($data["url"])),
intval($uid));
if (!$contact)
@ -479,23 +479,23 @@ function get_contact($url, $uid = 0) {
$contactid = $contact[0]["id"];
}
if ((count($contact) > 1) AND ($uid == 0) AND ($contactid != 0) AND ($url != ""))
q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d",
dbesc(normalise_link($url)),
intval($contactid));
require_once("Photo.php");
$photos = import_profile_photo($data["photo"],$uid,$contactid);
update_contact_avatar($data["photo"],$uid,$contactid);
q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s',
`addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
`name-date` = '%s', `uri-date` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
dbesc($photos[0]),
dbesc($photos[1]),
dbesc($photos[2]),
q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
`name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
dbesc($data["addr"]),
dbesc($data["alias"]),
dbesc($data["name"]),
dbesc($data["nick"]),
dbesc(datetime_convert()),
dbesc(datetime_convert()),
dbesc(datetime_convert()),
intval($contactid)
);
@ -662,4 +662,34 @@ function posts_from_contact($a, $contact_id) {
return $o;
}
/**
* @brief Returns a formatted location string from the given profile array
*
* @param array $profile Profile array (Generated from the "profile" table)
*
* @return string Location string
*/
function formatted_location($profile) {
$location = '';
if($profile['locality'])
$location .= $profile['locality'];
if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
if($location)
$location .= ', ';
$location .= $profile['region'];
}
if($profile['country-name']) {
if($location)
$location .= ', ';
$location .= $profile['country-name'];
}
return $location;
}
?>

View file

@ -720,65 +720,100 @@ function guess_image_type($filename, $fromcurl=false) {
}
function import_profile_photo($photo,$uid,$cid) {
/**
* @brief Updates the avatar links in a contact only if needed
*
* @param string $avatar Link to avatar picture
* @param int $uid User id of contact owner
* @param int $cid Contact id
*
* @return array Returns array of the different avatar sizes
*/
function update_contact_avatar($avatar,$uid,$cid) {
$a = get_app();
$r = q("SELECT `avatar`, `photo`, `thumb`, `micro` FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
if (!$r)
return false;
else
$data = array($r[0]["photo"], $r[0]["thumb"], $r[0]["micro"]);
$r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
intval($uid),
intval($cid)
);
if(count($r) && strlen($r[0]['resource-id'])) {
$hash = $r[0]['resource-id'];
}
else {
$hash = photo_new_resource();
}
if ($r[0]["avatar"] != $avatar) {
$photos = import_profile_photo($avatar,$uid,$cid, true);
$photo_failure = false;
if ($photos) {
q("UPDATE `contact` SET `avatar` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
dbesc($avatar), dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
dbesc(datetime_convert()), intval($cid));
return $photos;
}
}
$filename = basename($photo);
$img_str = fetch_url($photo,true);
return $data;
}
$type = guess_image_type($photo,true);
$img = new Photo($img_str, $type);
if($img->is_valid()) {
function import_profile_photo($photo,$uid,$cid, $quit_on_error = false) {
$img->scaleImageSquare(175);
$a = get_app();
$r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
$r = q("select `resource-id` from photo where `uid` = %d and `contact-id` = %d and `scale` = 4 and `album` = 'Contact Photos' limit 1",
intval($uid),
intval($cid)
);
if(count($r) && strlen($r[0]['resource-id'])) {
$hash = $r[0]['resource-id'];
} else {
$hash = photo_new_resource();
}
if($r === false)
$photo_failure = true;
$photo_failure = false;
$img->scaleImage(80);
$filename = basename($photo);
$img_str = fetch_url($photo,true);
$r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
if ($quit_on_error AND ($img_str == ""))
return false;
if($r === false)
$photo_failure = true;
$type = guess_image_type($photo,true);
$img = new Photo($img_str, $type);
if($img->is_valid()) {
$img->scaleImage(48);
$img->scaleImageSquare(175);
$r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
$r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 4 );
if($r === false)
$photo_failure = true;
if($r === false)
$photo_failure = true;
$photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
$thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
$micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
}
else
$photo_failure = true;
$img->scaleImage(80);
if($photo_failure) {
$photo = $a->get_baseurl() . '/images/person-175.jpg';
$thumb = $a->get_baseurl() . '/images/person-80.jpg';
$micro = $a->get_baseurl() . '/images/person-48.jpg';
}
$r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 5 );
return(array($photo,$thumb,$micro));
if($r === false)
$photo_failure = true;
$img->scaleImage(48);
$r = $img->store($uid, $cid, $hash, $filename, 'Contact Photos', 6 );
if($r === false)
$photo_failure = true;
$photo = $a->get_baseurl() . '/photo/' . $hash . '-4.' . $img->getExt();
$thumb = $a->get_baseurl() . '/photo/' . $hash . '-5.' . $img->getExt();
$micro = $a->get_baseurl() . '/photo/' . $hash . '-6.' . $img->getExt();
} else
$photo_failure = true;
if($photo_failure AND $quit_on_error)
return false;
if($photo_failure) {
$photo = $a->get_baseurl() . '/images/person-175.jpg';
$thumb = $a->get_baseurl() . '/images/person-80.jpg';
$micro = $a->get_baseurl() . '/images/person-48.jpg';
}
return(array($photo,$thumb,$micro));
}

View file

@ -235,7 +235,9 @@ function scrape_feed($url) {
$a = get_app();
$ret = array();
$s = fetch_url($url);
$cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
$s = fetch_url($url, false, $redirects, 0, Null, $cookiejar);
unlink($cookiejar);
$headers = $a->get_curl_headers();
$code = $a->get_curl_code();
@ -662,7 +664,9 @@ function probe_url($url, $mode = PROBE_NORMAL, $level = 1) {
$vcard['photo'] = $feedret['photo'];
require_once('library/simplepie/simplepie.inc');
$feed = new SimplePie();
$xml = fetch_url($poll);
$cookiejar = tempnam(get_temppath(), 'cookiejar-scrape-feed-');
$xml = fetch_url($poll, false, $redirects, 0, Null, $cookiejar);
unlink($cookiejar);
logger('probe_url: fetch feed: ' . $poll . ' returns: ' . $xml, LOGGER_DATA);
$a = get_app();

View file

@ -1551,6 +1551,8 @@
WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
AND `contact`.`id` = `item`.`contact-id`
AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
$sql_extra
AND `item`.`id`=%d",
intval($id)
@ -1579,7 +1581,8 @@
$_REQUEST["source"] = api_source();
item_post($a);
}
} else
throw new ForbiddenException();
// this should output the last post (the one we just posted).
$called_api = null;

View file

@ -30,7 +30,6 @@ function cron_run(&$argv, &$argc){
require_once('include/session.php');
require_once('include/datetime.php');
require_once('library/simplepie/simplepie.inc');
require_once('include/items.php');
require_once('include/Contact.php');
require_once('include/email.php');
@ -164,6 +163,9 @@ function cron_run(&$argv, &$argc){
// Repair missing Diaspora values in contacts
cron_repair_diaspora($a);
// Repair entries in the database
cron_repair_database();
$manual_id = 0;
$generation = 0;
$force = false;
@ -417,6 +419,23 @@ function cron_repair_diaspora(&$a) {
}
}
/**
* @brief Do some repairs in database entries
*
*/
function cron_repair_database() {
// Set the parent if it wasn't set. (Shouldn't happen - but does sometimes)
// This call is very "cheap" so we can do it at any time without a problem
q("UPDATE `item` INNER JOIN `item` AS `parent` ON `parent`.`uri` = `item`.`parent-uri` AND `parent`.`uid` = `item`.`uid` SET `item`.`parent` = `parent`.`id` WHERE `item`.`parent` = 0");
/// @todo
/// - remove thread entries without item
/// - remove sign entries without item
/// - remove children when parent got lost
/// - set contact-id in item when not present
}
if (array_search(__file__,get_included_files())===0){
cron_run($_SERVER["argv"],$_SERVER["argc"]);
killme();

View file

@ -453,6 +453,7 @@ function db_definition() {
"keywords" => array("type" => "text", "not null" => "1"),
"gender" => array("type" => "varchar(32)", "not null" => "1", "default" => ""),
"attag" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
"avatar" => array("type" => "varchar(255)", "not null" => "1", "default" => ""),
"photo" => array("type" => "text", "not null" => "1"),
"thumb" => array("type" => "text", "not null" => "1"),
"micro" => array("type" => "text", "not null" => "1"),

View file

@ -5,6 +5,7 @@ require_once('include/html2plain.php');
require_once("include/Scrape.php");
require_once('include/diaspora.php');
require_once("include/ostatus.php");
require_once("include/dfrn.php");
function delivery_run(&$argv, &$argc){
global $a, $db;
@ -264,8 +265,6 @@ function delivery_run(&$argv, &$argc){
if(count($r))
$contact = $r[0];
$hubxml = feed_hublinks();
if($contact['self'])
continue;
@ -278,138 +277,54 @@ function delivery_run(&$argv, &$argc){
case NETWORK_DFRN:
logger('notifier: '.$target_item["guid"].' dfrndelivery: ' . $contact['name']);
$feed_template = get_markup_template('atom_feed.tpl');
$mail_template = get_markup_template('atom_mail.tpl');
$atom = '';
$birthday = feed_birthday($owner['uid'],$owner['timezone']);
if(strlen($birthday))
$birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
$atom .= replace_macros($feed_template, array(
'$version' => xmlify(FRIENDICA_VERSION),
'$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
'$feed_title' => xmlify($owner['name']),
'$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
'$hub' => $hubxml,
'$salmon' => '', // private feed, we don't use salmon here
'$name' => xmlify($owner['name']),
'$profile_page' => xmlify($owner['url']),
'$photo' => xmlify($owner['photo']),
'$thumb' => xmlify($owner['thumb']),
'$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
'$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
'$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
'$birthday' => $birthday,
'$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
));
if($mail) {
$public_message = false; // mail is not public
$body = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
$atom .= replace_macros($mail_template, array(
'$name' => xmlify($owner['name']),
'$profile_page' => xmlify($owner['url']),
'$thumb' => xmlify($owner['thumb']),
'$item_id' => xmlify($item['uri']),
'$subject' => xmlify($item['title']),
'$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
'$content' => xmlify($body),
'$parent_id' => xmlify($item['parent-uri'])
));
} elseif($fsuggest) {
$public_message = false; // suggestions are not public
$sugg_template = get_markup_template('atom_suggest.tpl');
$atom .= replace_macros($sugg_template, array(
'$name' => xmlify($item['name']),
'$url' => xmlify($item['url']),
'$photo' => xmlify($item['photo']),
'$request' => xmlify($item['request']),
'$note' => xmlify($item['note'])
));
// We don't need this any more
q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
intval($item['id'])
);
} elseif($relocate) {
$public_message = false; // suggestions are not public
$sugg_template = get_markup_template('atom_relocate.tpl');
/* get site pubkey. this could be a new installation with no site keys*/
$pubkey = get_config('system','site_pubkey');
if(! $pubkey) {
$res = new_keypair(1024);
set_config('system','site_prvkey', $res['prvkey']);
set_config('system','site_pubkey', $res['pubkey']);
}
$rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
$photos = array();
$ext = Photo::supportedTypes();
foreach($rp as $p){
$photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
}
unset($rp, $ext);
$atom .= replace_macros($sugg_template, array(
'$name' => xmlify($owner['name']),
'$photo' => xmlify($photos[4]),
'$thumb' => xmlify($photos[5]),
'$micro' => xmlify($photos[6]),
'$url' => xmlify($owner['url']),
'$request' => xmlify($owner['request']),
'$confirm' => xmlify($owner['confirm']),
'$notify' => xmlify($owner['notify']),
'$poll' => xmlify($owner['poll']),
'$sitepubkey' => xmlify(get_config('system','site_pubkey')),
//'$pubkey' => xmlify($owner['pubkey']),
//'$prvkey' => xmlify($owner['prvkey']),
));
unset($photos);
} elseif($followup) {
if ($mail) {
$item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
$atom = dfrn::mail($item, $owner);
} elseif ($fsuggest) {
$atom = dfrn::fsuggest($item, $owner);
q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
} elseif ($relocate)
$atom = dfrn::relocate($owner, $uid);
elseif($followup) {
$msgitems = array();
foreach($items as $item) { // there is only one item
if(! $item['parent'])
if(!$item['parent'])
continue;
if($item['id'] == $item_id) {
logger('followup: item: ' . print_r($item,true), LOGGER_DATA);
$atom .= atom_entry($item,'text',null,$owner,false);
$msgitems[] = $item;
}
}
$atom = dfrn::entries($msgitems,$owner);
} else {
$msgitems = array();
foreach($items as $item) {
if(! $item['parent'])
if(!$item['parent'])
continue;
// private emails may be in included in public conversations. Filter them.
if(($public_message) && $item['private'] == 1)
if(($public_message) && $item['private'])
continue;
$item_contact = get_item_contact($item,$icontacts);
if(! $item_contact)
if(!$item_contact)
continue;
if($normal_mode) {
if($item_id == $item['id'] || $item['id'] == $item['parent'])
$atom .= atom_entry($item,'text',null,$owner,true,(($top_level) ? $contact['id'] : 0));
} else
$atom .= atom_entry($item,'text',null,$owner,true);
if($item_id == $item['id'] || $item['id'] == $item['parent']) {
$item["entry:comment-allow"] = true;
$item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
$msgitems[] = $item;
}
} else {
$item["entry:comment-allow"] = true;
$msgitems[] = $item;
}
}
$atom = dfrn::entries($msgitems,$owner);
}
$atom .= '</feed>' . "\r\n";
logger('notifier: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
logger('notifier: ' . $atom, LOGGER_DATA);
$basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
@ -458,7 +373,6 @@ function delivery_run(&$argv, &$argc){
if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level)
break;
require_once('library/simplepie/simplepie.inc');
logger('mod-delivery: local delivery');
local_delivery($x[0],$atom);
break;
@ -466,7 +380,7 @@ function delivery_run(&$argv, &$argc){
}
if(! was_recently_delayed($contact['id']))
$deliver_status = dfrn_deliver($owner,$contact,$atom);
$deliver_status = dfrn::deliver($owner,$contact,$atom);
else
$deliver_status = (-1);

1048
include/dfrn.php Normal file

File diff suppressed because it is too large Load diff

View file

@ -14,6 +14,7 @@ require_once('include/queue_fn.php');
require_once('include/lock.php');
require_once('include/threads.php');
require_once('mod/share.php');
require_once('include/enotify.php');
function diaspora_dispatch_public($msg) {
@ -728,7 +729,7 @@ function diaspora_request($importer,$xml) {
require_once('include/Photo.php');
$photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
update_contact_avatar($contact_record['photo'],$importer['uid'],$contact_record['id']);
// technically they are sharing with us (CONTACT_IS_SHARING),
// but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
@ -739,26 +740,17 @@ function diaspora_request($importer,$xml) {
else
$new_relation = CONTACT_IS_FOLLOWER;
$r = q("UPDATE `contact` SET
`photo` = '%s',
`thumb` = '%s',
`micro` = '%s',
`rel` = %d,
$r = q("UPDATE `contact` SET `rel` = %d,
`name-date` = '%s',
`uri-date` = '%s',
`avatar-date` = '%s',
`blocked` = 0,
`pending` = 0,
`writable` = 1
WHERE `id` = %d
",
dbesc($photos[0]),
dbesc($photos[1]),
dbesc($photos[2]),
intval($new_relation),
dbesc(datetime_convert()),
dbesc(datetime_convert()),
dbesc(datetime_convert()),
intval($contact_record['id'])
);
@ -826,6 +818,23 @@ function diaspora_plink($addr, $guid) {
return 'https://'.substr($addr,strpos($addr,'@')+1).'/posts/'.$guid;
}
function diaspora_repair_signature($signature, $handle = "", $level = 1) {
if ($signature == "")
return($signature);
if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
$signature = base64_decode($signature);
logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
// Do a recursive call to be able to fix even multiple levels
if ($level < 10)
$signature = diaspora_repair_signature($signature, $handle, ++$level);
}
return($signature);
}
function diaspora_post($importer,$xml,$msg) {
$a = get_app();
@ -1565,62 +1574,22 @@ function diaspora_comment($importer,$xml,$msg) {
//);
//}
if(($parent_item['origin']) && (! $parent_author_signature)) {
// If we are the origin of the parent we store the original signature and notify our followers
if($parent_item['origin']) {
$author_signature_base64 = base64_encode($author_signature);
$author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
intval($message_id),
dbesc($signed_data),
dbesc(base64_encode($author_signature)),
dbesc($author_signature_base64),
dbesc($diaspora_handle)
);
// if the message isn't already being relayed, notify others
// the existence of parent_author_signature means the parent_author or owner
// is already relaying.
// notify others
proc_run('php','include/notifier.php','comment-import',$message_id);
}
$myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
dbesc($parent_item['uri']),
intval($importer['uid'])
);
if(count($myconv)) {
$importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
foreach($myconv as $conv) {
// now if we find a match, it means we're in this conversation
if(! link_compare($conv['author-link'],$importer_url))
continue;
require_once('include/enotify.php');
$conv_parent = $conv['parent'];
notification(array(
'type' => NOTIFY_COMMENT,
'notify_flags' => $importer['notify-flags'],
'language' => $importer['language'],
'to_name' => $importer['username'],
'to_email' => $importer['email'],
'uid' => $importer['uid'],
'item' => $datarray,
'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
'source_name' => $datarray['author-name'],
'source_link' => $datarray['author-link'],
'source_photo' => $datarray['author-avatar'],
'verb' => ACTIVITY_POST,
'otype' => 'item',
'parent' => $conv_parent,
'parent_uri' => $parent_uri
));
// only send one notification
break;
}
}
return;
}
@ -1775,7 +1744,6 @@ function diaspora_conversation($importer,$xml,$msg) {
intval($conversation['id'])
);
require_once('include/enotify.php');
notification(array(
'type' => NOTIFY_MAIL,
'notify_flags' => $importer['notify-flags'],
@ -2226,21 +2194,21 @@ EOT;
// );
//}
if(! $parent_author_signature) {
// If we are the origin of the parent we store the original signature and notify our followers
if($parent_item['origin']) {
$author_signature_base64 = base64_encode($author_signature);
$author_signature_base64 = diaspora_repair_signature($author_signature_base64, $diaspora_handle);
q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
intval($message_id),
dbesc($signed_data),
dbesc(base64_encode($author_signature)),
dbesc($author_signature_base64),
dbesc($diaspora_handle)
);
}
// if the message isn't already being relayed, notify others
// the existence of parent_author_signature means the parent_author or owner
// is already relaying. The parent_item['origin'] indicates the message was created on our system
if(($parent_item['origin']) && (! $parent_author_signature))
// notify others
proc_run('php','include/notifier.php','comment-import',$message_id);
}
return;
}
@ -2336,8 +2304,7 @@ function diaspora_signed_retraction($importer,$xml,$msg) {
return;
}
}
else {
} else {
$sig_decode = base64_decode($sig);
@ -2371,7 +2338,7 @@ function diaspora_signed_retraction($importer,$xml,$msg) {
intval($r[0]['parent'])
);
if(count($p)) {
if(($p[0]['origin']) && (! $parent_author_signature)) {
if($p[0]['origin']) {
q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
$r[0]['id'],
dbesc($signed_data),
@ -2456,7 +2423,7 @@ function diaspora_profile($importer,$xml,$msg) {
require_once('include/Photo.php');
$images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
update_contact_avatar($image_url,$importer['uid'],$contact['id']);
// Generic birthday. We don't know the timezone. The year is irrelevant.
@ -2474,15 +2441,12 @@ function diaspora_profile($importer,$xml,$msg) {
/// @TODO Update name on item['author-name'] if the name changed. See consume_feed()
/// (Not doing this currently because D* protocol is scheduled for revision soon).
$r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
$r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
`location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
dbesc($name),
dbesc($nick),
dbesc($diaspora_handle),
dbesc(datetime_convert()),
dbesc($image_url),
dbesc($images[1]),
dbesc($images[2]),
dbesc(datetime_convert()),
dbesc($birthday),
dbesc($location),
dbesc($about),
@ -2819,7 +2783,7 @@ function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
// sign it
if($like)
$signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
$signed_text = $positive . ';' . $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $myaddr;
else
$signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
@ -2852,9 +2816,6 @@ function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
$myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
// $theiraddr = $contact['addr'];
$body = $item['body'];
$text = html_entity_decode(bb2diaspora($body));
// Diaspora doesn't support threaded comments, but some
// versions of Diaspora (i.e. Diaspora-pistos) support
// likes on comments
@ -2905,61 +2866,53 @@ function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
// fetch the original signature if the relayable was created by a Diaspora
// or DFRN user. Relayables for other networks are not supported.
/* $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
$r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
intval($item['id'])
);
if(count($r)) {
if(count($r)) {
$orig_sign = $r[0];
$signed_text = $orig_sign['signed_text'];
$authorsig = $orig_sign['signature'];
$handle = $orig_sign['signer'];
// Split the signed text
$signed_parts = explode(";", $signed_text);
// Remove the parent guid
array_shift($signed_parts);
// Remove the comment guid
array_shift($signed_parts);
// Remove the handle
array_pop($signed_parts);
// Glue the parts together
$text = implode(";", $signed_parts);
}
else {
// This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
// This means that the comment won't be accepted by newer Diaspora servers
// Author signature information (for likes, comments, and retractions of likes or comments,
// whether from Diaspora or Friendica) must be placed in the `sign` table before this
// function is called
logger('diaspora_send_relay: original author signature not found, cannot send relayable');
return;
}*/
$body = $item['body'];
$text = html_entity_decode(bb2diaspora($body));
/* Since the author signature is only checked by the parent, not by the relay recipients,
* I think it may not be necessary for us to do so much work to preserve all the original
* signatures. The important thing that Diaspora DOES need is the original creator's handle.
* Let's just generate that and forget about all the original author signature stuff.
*
* Note: this might be more of an problem if we want to support likes on comments for older
* versions of Diaspora (diaspora-pistos), but since there are a number of problems with
* doing that, let's ignore it for now.
*
* Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
* been done yet
*/
$handle = diaspora_handle_from_contact($item['contact-id']);
if(! $handle)
return;
$handle = diaspora_handle_from_contact($item['contact-id']);
if(! $handle)
return;
if($relay_retract)
$signed_text = $item['guid'] . ';' . $target_type;
elseif($like)
$signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
else
$signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
if($relay_retract)
$sender_signed_text = $item['guid'] . ';' . $target_type;
elseif($like)
$sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
else
$sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
$authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
}
// Sign the relayable with the top-level owner's signature
//
// We'll use the $sender_signed_text that we just created, instead of the $signed_text
// stored in the database, because that provides the best chance that Diaspora will
// be able to reconstruct the signed text the same way we did. This is particularly a
// concern for the comment, whose signed text includes the text of the comment. The
// smallest change in the text of the comment, including removing whitespace, will
// make the signature verification fail. Since we translate from BB code to Diaspora's
// markup at the top of this function, which is AFTER we placed the original $signed_text
// in the database, it's hazardous to trust the original $signed_text.
$parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
$parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
$msg = replace_macros($tpl,array(
'$guid' => xmlify($item['guid']),

View file

@ -76,11 +76,18 @@ function discover_poco_run(&$argv, &$argc){
update_suggestions();
elseif (($mode == 2) AND get_config('system','poco_completion'))
discover_users();
elseif (($mode == 1) AND ($search != "") and get_config('system','poco_local_search'))
elseif (($mode == 1) AND ($search != "") and get_config('system','poco_local_search')) {
discover_directory($search);
elseif (($mode == 0) AND ($search == "") and (get_config('system','poco_discovery') > 0))
gs_search_user($search);
} elseif (($mode == 0) AND ($search == "") and (get_config('system','poco_discovery') > 0)) {
// Query Friendica and Hubzilla servers for their users
poco_discover();
// Query GNU Social servers for their users ("statistics" addon has to be enabled on the GS server)
if (!get_config('system','ostatus_disabled'))
gs_discover();
}
logger('end '.$search);
return;
@ -128,7 +135,7 @@ function discover_users() {
else
$server_url = poco_detect_server($user["url"]);
if (poco_check_server($server_url, $gcontacts[0]["network"])) {
if (($server_url == "") OR poco_check_server($server_url, $gcontacts[0]["network"])) {
logger('Check user '.$user["url"]);
poco_last_updated($user["url"], true);
@ -191,6 +198,36 @@ function discover_directory($search) {
Cache::set("dirsearch:".$search, time(), CACHE_DAY);
}
/**
* @brief Search for GNU Social user with gstools.org
*
* @param str $search User name
*/
function gs_search_user($search) {
$a = get_app();
$url = "http://gstools.org/api/users_search/".urlencode($search);
$result = z_fetch_url($url);
if (!$result["success"])
return false;
$contacts = json_decode($result["body"]);
if ($contacts->status == 'ERROR')
return false;
foreach($contacts->data AS $user) {
$contact = probe_url($user->site_address."/".$user->name);
if ($contact["network"] != NETWORK_PHANTOM) {
$contact["about"] = $user->description;
update_gcontact($contact);
}
}
}
if (array_search(__file__,get_included_files())===0){
discover_poco_run($_SERVER["argv"],$_SERVER["argc"]);
killme();

View file

@ -633,4 +633,129 @@ function notification($params) {
}
/**
* @brief Checks for item related notifications and sends them
*
* @param int $itemid ID of the item for which the check should be done
* @param int $uid User ID
* @param str $defaulttype (Optional) Forces a notification with this type.
*/
function check_item_notification($itemid, $uid, $defaulttype = "") {
$notification_data = array("uid" => $uid, "profiles" => array());
call_hooks('check_item_notification', $notification_data);
$profiles = $notification_data["profiles"];
$user = q("SELECT `notify-flags`, `language`, `username`, `email` FROM `user` WHERE `uid` = %d", intval($uid));
if (!$user)
return false;
$owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
if (!$owner)
return false;
$profiles[] = $owner[0]["url"];
$profiles2 = array();
foreach ($profiles AS $profile) {
$profiles2[] = normalise_link($profile);
$profiles2[] = str_replace("http://", "https://", normalise_link($profile));
}
$profiles = $profiles2;
$profile_list = "";
foreach ($profiles AS $profile) {
if ($profile_list != "")
$profile_list .= "', '";
$profile_list .= dbesc($profile);
}
$profile_list = "'".$profile_list."'";
// Only act if it is a "real" post
// We need the additional check for the "local_profile" because of mixed situations on connector networks
$item = q("SELECT `id`, `mention`, `tag`,`parent`, `title`, `body`, `author-name`, `author-link`, `author-avatar`, `guid`,
`parent-uri`, `uri`, `contact-id`
FROM `item` WHERE `id` = %d AND `verb` IN ('%s', '') AND `type` != 'activity' AND
NOT (`author-link` IN ($profile_list)) LIMIT 1",
intval($itemid), dbesc(ACTIVITY_POST));
if (!$item)
return false;
// Generate the notification array
$params = array();
$params["uid"] = $uid;
$params["notify_flags"] = $user[0]["notify-flags"];
$params["language"] = $user[0]["language"];
$params["to_name"] = $user[0]["username"];
$params["to_email"] = $user[0]["email"];
$params["item"] = $item[0];
$params["parent"] = $item[0]["parent"];
$params["link"] = App::get_baseurl().'/display/'.urlencode($item[0]["guid"]);
$params["otype"] = 'item';
$params["source_name"] = $item[0]["author-name"];
$params["source_link"] = $item[0]["author-link"];
$params["source_photo"] = $item[0]["author-avatar"];
if ($item[0]["parent-uri"] === $item[0]["uri"]) {
// Send a notification for every new post?
$r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
intval($item[0]['contact-id']),
intval($uid)
);
$send_notification = count($r);
if (!$send_notification) {
$tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
if (count($tags)) {
foreach ($tags AS $tag) {
$r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
normalise_link($tag["url"]), intval($uid));
if (count($r))
$send_notification = true;
}
}
}
if ($send_notification) {
$params["type"] = NOTIFY_SHARE;
$params["verb"] = ACTIVITY_TAG;
}
}
// Is the user mentioned in this post?
$tagged = false;
foreach ($profiles AS $profile) {
if (strpos($item[0]["tag"], "=".$profile."]") OR strpos($item[0]["body"], "=".$profile."]"))
$tagged = true;
}
if ($item[0]["mention"] OR $tagged OR ($defaulttype == NOTIFY_TAGSELF)) {
$params["type"] = NOTIFY_TAGSELF;
$params["verb"] = ACTIVITY_TAG;
}
// Is it a post that the user had started or where he interacted?
$parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
(`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
LIMIT 1",
intval($item[0]["parent"]), intval($uid));
if ($parent AND !isset($params["type"])) {
$params["type"] = NOTIFY_COMMENT;
$params["verb"] = ACTIVITY_POST;
}
if (isset($params["type"]))
notification($params);
}
?>

View file

@ -61,7 +61,7 @@ function format_event_html($ev, $simple = false) {
. bbcode($ev['location'])
. '</span></p>' . "\r\n";
if (strpos($ev['location'], "[map")===False) {
if (strpos($ev['location'], "[map") !== False) {
$map = generate_named_map($ev['location']);
if ($map!==$ev['location']) $o.=$map;
}

View file

@ -18,7 +18,6 @@ function expire_run(&$argv, &$argc){
require_once('include/session.php');
require_once('include/datetime.php');
require_once('library/simplepie/simplepie.inc');
require_once('include/items.php');
require_once('include/Contact.php');

View file

@ -264,24 +264,8 @@ function new_contact($uid,$url,$interactive = false) {
require_once("include/Photo.php");
$photos = import_profile_photo($ret['photo'],$uid,$contact_id);
$r = q("UPDATE `contact` SET `photo` = '%s',
`thumb` = '%s',
`micro` = '%s',
`name-date` = '%s',
`uri-date` = '%s',
`avatar-date` = '%s'
WHERE `id` = %d",
dbesc($photos[0]),
dbesc($photos[1]),
dbesc($photos[2]),
dbesc(datetime_convert()),
dbesc(datetime_convert()),
dbesc(datetime_convert()),
intval($contact_id)
);
// Update the avatar
update_contact_avatar($ret['photo'],$uid,$contact_id);
// pull feed and consume it, which should subscribe to the hub.

View file

@ -42,6 +42,9 @@ function get_forumlist($uid, $showhidden = true, $lastitem, $showprivate = false
intval($uid)
);
if (!$contacts)
return($forumlist);
foreach($contacts as $contact) {
$forumlist[] = array(
'url' => $contact['url'],

View file

@ -33,7 +33,7 @@ function gprobe_run(&$argv, &$argc){
$url = hex2bin($argv[1]);
$r = q("select * from gcontact where nurl = '%s' limit 1",
$r = q("SELECT `id`, `url`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 1",
dbesc(normalise_link($url))
);
@ -58,21 +58,16 @@ function gprobe_run(&$argv, &$argc){
if (is_null($result))
Cache::set("gprobe:".$urlparts["host"],serialize($arr));
if(count($arr) && x($arr,'network') && $arr['network'] === NETWORK_DFRN) {
q("insert into `gcontact` (`name`,`url`,`nurl`,`photo`)
values ( '%s', '%s', '%s', '%s') ",
dbesc($arr['name']),
dbesc($arr['url']),
dbesc(normalise_link($arr['url'])),
dbesc($arr['photo'])
);
}
$r = q("select * from gcontact where nurl = '%s' limit 1",
if (!in_array($result["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))
update_gcontact($arr);
$r = q("SELECT `id`, `url`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 1",
dbesc(normalise_link($url))
);
}
if(count($r))
poco_load(0,0,$r[0]['id'], str_replace('/profile/','/poco/',$r[0]['url']));
if ($r[0]["network"] == NETWORK_DFRN)
poco_load(0,0,$r[0]['id'], str_replace('/profile/','/poco/',$r[0]['url']));
logger("gprobe end for ".normalise_link($url), LOGGER_DEBUG);
return;

File diff suppressed because it is too large Load diff

View file

@ -279,6 +279,9 @@ function store_diaspora_like_retract_sig($activity, $item, $like_item, $contact)
$contact_baseurl = substr($contact['url'], $contact_baseurl_start, $contact_baseurl_length);
$diaspora_handle = $contact['nick'] . '@' . $contact_baseurl;
// This code could never had worked (the return values form the queries were used in a wrong way.
// Additionally it is needlessly complicated. Either the contact is owner or not. And we have this data already.
/*
// Get contact's private key if he's a user of the local Friendica server
$r = q("SELECT `contact`.`uid` FROM `contact` WHERE `url` = '%s' AND `self` = 1 LIMIT 1",
dbesc($contact['url'])
@ -289,9 +292,15 @@ function store_diaspora_like_retract_sig($activity, $item, $like_item, $contact)
$r = q("SELECT prvkey FROM user WHERE uid = %d LIMIT 1",
intval($contact_uid)
);
*/
// Is the contact the owner? Then fetch the private key
if ($contact['self'] AND ($contact['uid'] > 0)) {
$r = q("SELECT prvkey FROM user WHERE uid = %d LIMIT 1",
intval($contact['uid'])
);
if( $r)
$authorsig = base64_encode(rsa_sign($signed_text,$r['prvkey'],'sha256'));
if($r)
$authorsig = base64_encode(rsa_sign($signed_text,$r[0]['prvkey'],'sha256'));
}
if(! isset($authorsig))
@ -329,6 +338,10 @@ function store_diaspora_like_sig($activity, $post_type, $contact, $post_id) {
$contact_baseurl = substr($contact['url'], $contact_baseurl_start, $contact_baseurl_length);
$diaspora_handle = $contact['nick'] . '@' . $contact_baseurl;
// This code could never had worked (the return values form the queries were used in a wrong way.
// Additionally it is needlessly complicated. Either the contact is owner or not. And we have this data already.
/*
// Get contact's private key if he's a user of the local Friendica server
$r = q("SELECT `contact`.`uid` FROM `contact` WHERE `url` = '%s' AND `self` = 1 LIMIT 1",
dbesc($contact['url'])
@ -343,6 +356,17 @@ function store_diaspora_like_sig($activity, $post_type, $contact, $post_id) {
if( $r)
$contact_uprvkey = $r['prvkey'];
}
*/
// Is the contact the owner? Then fetch the private key
if ($contact['self'] AND ($contact['uid'] > 0)) {
$r = q("SELECT prvkey FROM user WHERE uid = %d LIMIT 1",
intval($contact['uid'])
);
if($r)
$contact_uprvkey = $r[0]['prvkey'];
}
$r = q("SELECT guid, parent FROM `item` WHERE id = %d LIMIT 1",
intval($post_id)
@ -353,7 +377,7 @@ function store_diaspora_like_sig($activity, $post_type, $contact, $post_id) {
intval($r[0]['parent'])
);
if( $p) {
$signed_text = $r[0]['guid'] . ';Post;' . $p[0]['guid'] . ';true;' . $diaspora_handle;
$signed_text = 'true;'.$r[0]['guid'].';Post;'.$p[0]['guid'].';'.$diaspora_handle;
if(isset($contact_uprvkey))
$authorsig = base64_encode(rsa_sign($signed_text,$contact_uprvkey,'sha256'));

View file

@ -42,6 +42,7 @@ if(!function_exists('z_fetch_url')){
* @return array an assoziative array with:
* * \e int \b return_code => HTTP return code or 0 if timeout or failure
* * \e boolean \b success => boolean true (if HTTP 2xx result) or false
* * \e string \b redirect_url => in case of redirect, content was finally retrieved from this URL
* * \e string \b header => HTTP headers
* * \e string \b body => fetched content
*/
@ -116,6 +117,9 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
// if it throws any errors.
$s = @curl_exec($ch);
if (curl_errno($ch) !== CURLE_OK) {
logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
}
$base = $s;
$curl_info = @curl_getinfo($ch);
@ -133,6 +137,10 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
$base = substr($base,strlen($chunk));
}
$a->set_curl_code($http_code);
$a->set_curl_content_type($curl_info['content_type']);
$a->set_curl_headers($header);
if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
$new_location_info = @parse_url($curl_info["redirect_url"]);
$old_location_info = @parse_url($curl_info["url"]);
@ -160,13 +168,13 @@ function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
$a->set_curl_content_type($curl_info['content_type']);
$body = substr($s,strlen($header));
$a->set_curl_headers($header);
$rc = intval($http_code);
$ret['return_code'] = $rc;
$ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
$ret['redirect_url'] = $url;
if(! $ret['success']) {
$ret['error'] = curl_error($ch);
$ret['debug'] = $curl_info;

View file

@ -535,7 +535,7 @@ function notifier_run(&$argv, &$argc){
if($public_message) {
if (!$followup)
if (!$followup AND $top_level)
$r0 = diaspora_fetch_relay();
else
$r0 = array();

View file

@ -27,7 +27,6 @@ function onepoll_run(&$argv, &$argc){
require_once('include/session.php');
require_once('include/datetime.php');
require_once('library/simplepie/simplepie.inc');
require_once('include/items.php');
require_once('include/Contact.php');
require_once('include/email.php');
@ -335,7 +334,9 @@ function onepoll_run(&$argv, &$argc){
if($contact['rel'] == CONTACT_IS_FOLLOWER || $contact['blocked'] || $contact['readonly'])
return;
$xml = fetch_url($contact['poll']);
$cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
$xml = fetch_url($contact['poll'], false, $redirects, 0, Null, $cookiejar);
unlink($cookiejar);
}
elseif($contact['network'] === NETWORK_MAIL || $contact['network'] === NETWORK_MAIL2) {

View file

@ -127,7 +127,8 @@ function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch)
$author["owner-link"] = $author["author-link"];
$author["owner-avatar"] = $author["author-avatar"];
if ($r AND !$onlyfetch) {
// Only update the contacts if it is an OStatus contact
if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
// Update contact data
$value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
@ -158,24 +159,21 @@ function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch)
logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d AND `network` = '%s'",
q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
dbesc(datetime_convert()), intval($contact["id"]), dbesc(NETWORK_OSTATUS));
dbesc(datetime_convert()), intval($contact["id"]));
poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
"", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
}
if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['photo'])) {
if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
$photos = import_profile_photo($author["author-avatar"], $importer["uid"], $contact["id"]);
q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d AND `network` = '%s'",
dbesc($author["author-avatar"]), dbesc($photos[1]), dbesc($photos[2]),
dbesc(datetime_convert()), intval($contact["id"]), dbesc(NETWORK_OSTATUS));
update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
}
/// @todo Add the "addr" field
$contact["generation"] = 2;
$contact["photo"] = $author["author-avatar"];
@ -558,29 +556,6 @@ function ostatus_import($xml,$importer,&$contact, &$hub) {
}
logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
$item["id"] = $item_id;
if ($mention) {
$u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
$r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($item_id));
notification(array(
'type' => NOTIFY_TAGSELF,
'notify_flags' => $u[0]["notify-flags"],
'language' => $u[0]["language"],
'to_name' => $u[0]["username"],
'to_email' => $u[0]["email"],
'uid' => $item["uid"],
'item' => $item,
'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item_id)),
'source_name' => $item["author-name"],
'source_link' => $item["author-link"],
'source_photo' => $item["author-avatar"],
'verb' => ACTIVITY_TAG,
'otype' => 'item',
'parent' => $r[0]["parent"]
));
}
}
}
@ -1025,28 +1000,6 @@ function ostatus_completion($conversation_url, $uid, $item = array()) {
// Add the conversation entry (but don't fetch the whole conversation)
ostatus_store_conversation($newitem, $conversation_url);
if ($mention) {
$u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($uid));
$r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($newitem));
notification(array(
'type' => NOTIFY_TAGSELF,
'notify_flags' => $u[0]["notify-flags"],
'language' => $u[0]["language"],
'to_name' => $u[0]["username"],
'to_email' => $u[0]["email"],
'uid' => $uid,
'item' => $arr,
'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($newitem)),
'source_name' => $arr["author-name"],
'source_link' => $arr["author-link"],
'source_photo' => $arr["author-avatar"],
'verb' => ACTIVITY_TAG,
'otype' => 'item',
'parent' => $r[0]["parent"]
));
}
// If the newly created item is the top item then change the parent settings of the thread
// This shouldn't happen anymore. This is supposed to be absolote.
if ($arr["uri"] == $first_id) {
@ -1121,7 +1074,7 @@ function get_reshared_guid($item) {
return $guid;
}
function xml_add_element($doc, $parent, $element, $value = "", $attributes = array()) {
function xml_create_element($doc, $element, $value = "", $attributes = array()) {
$element = $doc->createElement($element, xmlify($value));
foreach ($attributes AS $key => $value) {
@ -1129,7 +1082,11 @@ function xml_add_element($doc, $parent, $element, $value = "", $attributes = arr
$attribute->value = xmlify($value);
$element->appendChild($attribute);
}
return $element;
}
function xml_add_element($doc, $parent, $element, $value = "", $attributes = array()) {
$element = xml_create_element($doc, $element, $value, $attributes);
$parent->appendChild($element);
}

View file

@ -39,8 +39,10 @@ function poller_run(&$argv, &$argc){
}
// Checking the number of workers
if (poller_too_much_workers(1))
if (poller_too_much_workers(1)) {
poller_kill_stale_workers();
return;
}
if(($argc <= 1) OR ($argv[1] != "no_cron")) {
// Run the cron job that calls all other jobs
@ -50,16 +52,7 @@ function poller_run(&$argv, &$argc){
proc_run("php","include/cronhooks.php");
// Cleaning dead processes
$r = q("SELECT DISTINCT(`pid`) FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
foreach($r AS $pid)
if (!posix_kill($pid["pid"], 0))
q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
intval($pid["pid"]));
else {
/// @TODO Kill long running processes
/// But: Update processes (like the database update) mustn't be killed
}
poller_kill_stale_workers();
} else
// Sleep four seconds before checking for running processes again to avoid having too many workers
sleep(4);
@ -124,6 +117,32 @@ function poller_run(&$argv, &$argc){
}
/**
* @brief fix the queue entry if the worker process died
*
*/
function poller_kill_stale_workers() {
$r = q("SELECT `pid`, `executed` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
foreach($r AS $pid)
if (!posix_kill($pid["pid"], 0))
q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
intval($pid["pid"]));
else {
// Kill long running processes
$duration = (time() - strtotime($pid["executed"])) / 60;
if ($duration > 180) {
logger("Worker process ".$pid["pid"]." took more than 3 hours. It will be killed now.");
posix_kill($pid["pid"], SIGTERM);
// Question: If a process is stale: Should we remove it or should we reschedule it?
// By now we rescheduling it. It's maybe not the wisest decision?
q("UPDATE `workerqueue` SET `executed` = '0000-00-00 00:00:00', `pid` = 0 WHERE `pid` = %d",
intval($pid["pid"]));
} else
logger("Worker process ".$pid["pid"]." now runs for ".round($duration)." minutes. That's okay.", LOGGER_DEBUG);
}
}
function poller_too_much_workers($stage) {
$queues = get_config("system", "worker_queues");

View file

@ -3,6 +3,7 @@
require_once('include/datetime.php');
require_once('include/diaspora.php');
require_once('include/queue_fn.php');
require_once('include/Contact.php');
function profile_change() {
@ -53,19 +54,7 @@ function profile_change() {
$about = xmlify($profile['about']);
require_once('include/bbcode.php');
$about = xmlify(strip_tags(bbcode($about)));
$location = '';
if($profile['locality'])
$location .= $profile['locality'];
if($profile['region']) {
if($location)
$location .= ', ';
$location .= $profile['region'];
}
if($profile['country-name']) {
if($location)
$location .= ', ';
$location .= $profile['country-name'];
}
$location = formatted_location($profile);
$location = xmlify($location);
$tags = '';
if($profile['pub_keywords']) {

View file

@ -1,6 +1,7 @@
<?php
require_once("boot.php");
require_once('include/queue_fn.php');
require_once('include/dfrn.php');
function queue_run(&$argv, &$argc){
global $a, $db;
@ -52,6 +53,8 @@ function queue_run(&$argv, &$argc){
$queue_id = 0;
$deadguys = array();
$deadservers = array();
$serverlist = array();
logger('queue: start');
@ -95,7 +98,7 @@ function queue_run(&$argv, &$argc){
// For the first 12 hours we'll try to deliver every 15 minutes
// After that, we'll only attempt delivery once per hour.
$r = q("SELECT `id` FROM `queue` WHERE (( `created` > UTC_TIMESTAMP() - INTERVAL 12 HOUR && `last` < UTC_TIMESTAMP() - INTERVAL 15 MINUTE ) OR ( `last` < UTC_TIMESTAMP() - INTERVAL 1 HOUR ))");
$r = q("SELECT `id` FROM `queue` WHERE ((`created` > UTC_TIMESTAMP() - INTERVAL 12 HOUR && `last` < UTC_TIMESTAMP() - INTERVAL 15 MINUTE) OR (`last` < UTC_TIMESTAMP() - INTERVAL 1 HOUR)) ORDER BY `cid`, `created`");
}
if(! $r){
return;
@ -116,7 +119,7 @@ function queue_run(&$argv, &$argc){
// so check again if this entry still needs processing
if($queue_id) {
$qi = q("select * from queue where `id` = %d limit 1",
$qi = q("SELECT * FROM `queue` WHERE `id` = %d LIMIT 1",
intval($queue_id)
);
}
@ -142,8 +145,18 @@ function queue_run(&$argv, &$argc){
continue;
}
if (!poco_reachable($c[0]['url'])) {
logger('queue: skipping probably dead url: ' . $c[0]['url']);
$server = poco_detect_server($c[0]['url']);
if (($server != "") AND !in_array($server, $serverlist)) {
logger("Check server ".$server." (".$c[0]["network"].")");
if (!poco_check_server($server, $c[0]["network"], true))
$deadservers[] = $server;
$serverlist[] = $server;
}
if (($server != "") AND in_array($server, $deadservers)) {
logger('queue: skipping known dead server: '.$server);
update_queue_time($q_item['id']);
continue;
}
@ -166,37 +179,39 @@ function queue_run(&$argv, &$argc){
switch($contact['network']) {
case NETWORK_DFRN:
logger('queue: dfrndelivery: item ' . $q_item['id'] . ' for ' . $contact['name']);
$deliver_status = dfrn_deliver($owner,$contact,$data);
logger('queue: dfrndelivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>');
$deliver_status = dfrn::deliver($owner,$contact,$data);
if($deliver_status == (-1)) {
update_queue_time($q_item['id']);
$deadguys[] = $contact['notify'];
}
else {
} else
remove_queue_item($q_item['id']);
}
break;
case NETWORK_OSTATUS:
if($contact['notify']) {
logger('queue: slapdelivery: item ' . $q_item['id'] . ' for ' . $contact['name']);
logger('queue: slapdelivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>');
$deliver_status = slapper($owner,$contact['notify'],$data);
if($deliver_status == (-1))
if($deliver_status == (-1)) {
update_queue_time($q_item['id']);
else
$deadguys[] = $contact['notify'];
} else
remove_queue_item($q_item['id']);
}
break;
case NETWORK_DIASPORA:
if($contact['notify']) {
logger('queue: diaspora_delivery: item ' . $q_item['id'] . ' for ' . $contact['name']);
logger('queue: diaspora_delivery: item '.$q_item['id'].' for '.$contact['name'].' <'.$contact['url'].'>');
$deliver_status = diaspora_transmit($owner,$contact,$data,$public,true);
if($deliver_status == (-1))
if($deliver_status == (-1)) {
update_queue_time($q_item['id']);
else
$deadguys[] = $contact['notify'];
} else
remove_queue_item($q_item['id']);
}
break;
@ -212,6 +227,7 @@ function queue_run(&$argv, &$argc){
break;
}
logger('Deliver status '.$deliver_status.' for item '.$q_item['id'].' to '.$contact['name'].' <'.$contact['url'].'>');
}
return;

View file

@ -289,93 +289,25 @@ function poco_check($profile_url, $name, $network, $profile_photo, $about, $loca
poco_check_server($server_url, $network);
if(count($x)) {
$gcid = $x[0]['id'];
$gcontact = array("url" => $profile_url,
"addr" => $addr,
"alias" => $alias,
"name" => $name,
"network" => $network,
"photo" => $profile_photo,
"about" => $about,
"location" => $location,
"gender" => $gender,
"keywords" => $keywords,
"server_url" => $server_url,
"connect" => $connect_url,
"notify" => $notify,
"updated" => $updated,
"generation" => $generation);
if (($location == "") AND ($x[0]['location'] != ""))
$location = $x[0]['location'];
$gcid = update_gcontact($gcontact);
if (($about == "") AND ($x[0]['about'] != ""))
$about = $x[0]['about'];
if (($gender == "") AND ($x[0]['gender'] != ""))
$gender = $x[0]['gender'];
if (($keywords == "") AND ($x[0]['keywords'] != ""))
$keywords = $x[0]['keywords'];
if (($addr == "") AND ($x[0]['addr'] != ""))
$addr = $x[0]['addr'];
if (($alias == "") AND ($x[0]['alias'] != ""))
$alias = $x[0]['alias'];
if (($notify == "") AND ($x[0]['notify'] != ""))
$notify = $x[0]['notify'];
if (($generation == 0) AND ($x[0]['generation'] > 0))
$generation = $x[0]['generation'];
if($x[0]['name'] != $name || $x[0]['photo'] != $profile_photo || $x[0]['updated'] < $updated) {
q("UPDATE `gcontact` SET `name` = '%s', `addr` = '%s', `network` = '%s', `photo` = '%s', `connect` = '%s', `url` = '%s', `server_url` = '%s',
`updated` = '%s', `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s', `generation` = %d,
`alias` = '$s', `notify` = '%s'
WHERE (`generation` >= %d OR `generation` = 0) AND `nurl` = '%s'",
dbesc($name),
dbesc($addr),
dbesc($network),
dbesc($profile_photo),
dbesc($connect_url),
dbesc($profile_url),
dbesc($server_url),
dbesc($updated),
dbesc($location),
dbesc($about),
dbesc($keywords),
dbesc($gender),
dbesc($alias),
dbesc($notify),
intval($generation),
intval($generation),
dbesc(normalise_link($profile_url))
);
}
} else {
// Maybe another process had inserted the entry after the first check, so it again
$x = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
dbesc(normalise_link($profile_url))
);
if(!$x) {
q("INSERT INTO `gcontact` (`name`, `nick`, `addr`, `network`, `url`, `nurl`, `photo`, `connect`, `server_url`, `created`, `updated`, `location`, `about`, `keywords`, `gender`, `alias`, `notify`, `generation`)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)",
dbesc($name),
dbesc($nick),
dbesc($addr),
dbesc($network),
dbesc($profile_url),
dbesc(normalise_link($profile_url)),
dbesc($profile_photo),
dbesc($connect_url),
dbesc($server_url),
dbesc(datetime_convert()),
dbesc($updated),
dbesc($location),
dbesc($about),
dbesc($keywords),
dbesc($gender),
dbesc($alias),
dbesc($notify),
intval($generation)
);
$x = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
dbesc(normalise_link($profile_url))
);
}
if(count($x))
$gcid = $x[0]['id'];
}
if(! $gcid)
if(!$gcid)
return $gcid;
$r = q("SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
@ -402,13 +334,6 @@ function poco_check($profile_url, $name, $network, $profile_photo, $about, $loca
);
}
// For unknown reasons there are sometimes duplicates
//q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d AND
// NOT EXISTS (SELECT `gcid` FROM `glink` WHERE `gcid` = `gcontact`.`id`)",
// dbesc(normalise_link($profile_url)),
// intval($gcid)
//);
return $gcid;
}
@ -721,6 +646,10 @@ function poco_to_boolean($val) {
function poco_check_server($server_url, $network = "", $force = false) {
// Unify the server address
$server_url = trim($server_url, "/");
$server_url = str_replace("/index.php", "", $server_url);
if ($server_url == "")
return false;
@ -792,19 +721,23 @@ function poco_check_server($server_url, $network = "", $force = false) {
// Test for Diaspora
$serverret = z_fetch_url($server_url);
$lines = explode("\n",$serverret["header"]);
if(count($lines))
foreach($lines as $line) {
$line = trim($line);
if(stristr($line,'X-Diaspora-Version:')) {
$platform = "Diaspora";
$version = trim(str_replace("X-Diaspora-Version:", "", $line));
$version = trim(str_replace("x-diaspora-version:", "", $version));
$network = NETWORK_DIASPORA;
$versionparts = explode("-", $version);
$version = $versionparts[0];
if (!$serverret["success"] OR ($serverret["body"] == ""))
$failure = true;
else {
$lines = explode("\n",$serverret["header"]);
if(count($lines))
foreach($lines as $line) {
$line = trim($line);
if(stristr($line,'X-Diaspora-Version:')) {
$platform = "Diaspora";
$version = trim(str_replace("X-Diaspora-Version:", "", $line));
$version = trim(str_replace("x-diaspora-version:", "", $version));
$network = NETWORK_DIASPORA;
$versionparts = explode("-", $version);
$version = $versionparts[0];
}
}
}
}
}
if (!$failure) {
@ -1315,18 +1248,30 @@ function poco_discover_federation() {
return;
}
// Discover Friendica, Hubzilla and Diaspora servers
$serverdata = fetch_url("http://the-federation.info/pods.json");
if (!$serverdata)
return;
if ($serverdata) {
$servers = json_decode($serverdata);
$servers = json_decode($serverdata);
foreach($servers->pods AS $server)
poco_check_server("https://".$server->host);
}
foreach($servers->pods AS $server)
poco_check_server("https://".$server->host);
// Discover GNU Social Servers
if (!get_config('system','ostatus_disabled')) {
$serverdata = "http://gstools.org/api/get_open_instances/";
$result = z_fetch_url($serverdata);
if ($result["success"]) {
$servers = json_decode($result["body"]);
foreach($servers->data AS $server)
poco_check_server($server->instance_address);
}
}
set_config('poco','last_federation_discovery', time());
}
function poco_discover($complete = false) {
@ -1520,7 +1465,7 @@ function get_gcontact_id($contact) {
if ($contact["network"] == NETWORK_STATUSNET)
$contact["network"] = NETWORK_OSTATUS;
$r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
$r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
dbesc(normalise_link($contact["url"])));
if ($r)
@ -1542,13 +1487,18 @@ function get_gcontact_id($contact) {
intval($contact["generation"])
);
$r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
$r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
dbesc(normalise_link($contact["url"])));
if ($r)
$gcontact_id = $r[0]["id"];
}
if ((count($r) > 1) AND ($gcontact_id > 0) AND ($contact["url"] != ""))
q("DELETE FROM `gcontact` WHERE `nurl` = '%s' AND `id` != %d",
dbesc(normalise_link($contact["url"])),
intval($gcontact_id));
return $gcontact_id;
}
@ -1567,78 +1517,55 @@ function update_gcontact($contact) {
if (!$gcontact_id)
return false;
$r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`, `hide`, `nsfw`, `network`, `alias`, `notify`, `url`
$r = q("SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
`hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
FROM `gcontact` WHERE `id` = %d LIMIT 1",
intval($gcontact_id));
if ($contact["generation"] == 0)
$contact["generation"] = $r[0]["generation"];
// Get all field names
$fields = array();
foreach ($r[0] AS $field => $data)
$fields[$field] = $data;
if ($contact["photo"] == "")
$contact["photo"] = $r[0]["photo"];
unset($fields["url"]);
unset($fields["updated"]);
if ($contact["name"] == "")
$contact["name"] = $r[0]["name"];
if ($contact["nick"] == "")
$contact["nick"] = $r[0]["nick"];
if ($contact["addr"] == "")
$contact["addr"] = $r[0]["addr"];
if ($contact["location"] =="")
$contact["location"] = $r[0]["location"];
if ($contact["about"] =="")
$contact["about"] = $r[0]["about"];
if ($contact["birthday"] =="")
$contact["birthday"] = $r[0]["birthday"];
if ($contact["gender"] =="")
$contact["gender"] = $r[0]["gender"];
if ($contact["keywords"] =="")
$contact["keywords"] = $r[0]["keywords"];
if (!isset($contact["hide"]))
$contact["hide"] = $r[0]["hide"];
if (!isset($contact["nsfw"]))
$contact["nsfw"] = $r[0]["nsfw"];
if ($contact["network"] =="")
$contact["network"] = $r[0]["network"];
if ($contact["alias"] =="")
$contact["alias"] = $r[0]["alias"];
if ($contact["url"] =="")
$contact["url"] = $r[0]["url"];
if ($contact["notify"] =="")
$contact["notify"] = $r[0]["notify"];
// assign all unassigned fields from the database entry
foreach ($fields AS $field => $data)
if (!isset($contact[$field]))
$contact[$field] = $r[0][$field];
if ($contact["network"] == NETWORK_STATUSNET)
$contact["network"] = NETWORK_OSTATUS;
if (($contact["photo"] != $r[0]["photo"]) OR ($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["addr"] != $r[0]["addr"]) OR
($contact["birthday"] != $r[0]["birthday"]) OR ($contact["gender"] != $r[0]["gender"]) OR ($contact["keywords"] != $r[0]["keywords"]) OR
($contact["hide"] != $r[0]["hide"]) OR ($contact["nsfw"] != $r[0]["nsfw"]) OR ($contact["network"] != $r[0]["network"]) OR
($contact["alias"] != $r[0]["alias"]) OR ($contact["notify"] != $r[0]["notify"]) OR ($contact["url"] != $r[0]["url"]) OR
($contact["location"] != $r[0]["location"]) OR ($contact["about"] != $r[0]["about"]) OR ($contact["generation"] < $r[0]["generation"])) {
if (!isset($contact["updated"]))
$contact["updated"] = datetime_convert();
// Check if any field changed
$update = false;
unset($fields["generation"]);
foreach ($fields AS $field => $data)
if ($contact[$field] != $r[0][$field])
$update = true;
if ($contact["generation"] < $r[0]["generation"])
$update = true;
if ($update) {
q("UPDATE `gcontact` SET `photo` = '%s', `name` = '%s', `nick` = '%s', `addr` = '%s', `network` = '%s',
`birthday` = '%s', `gender` = '%s', `keywords` = %d, `hide` = %d, `nsfw` = %d,
`alias` = '%s', `notify` = '%s', `url` = '%s',
`location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s'
`location` = '%s', `about` = '%s', `generation` = %d, `updated` = '%s',
`server_url` = '%s', `connect` = '%s'
WHERE `nurl` = '%s' AND (`generation` = 0 OR `generation` >= %d)",
dbesc($contact["photo"]), dbesc($contact["name"]), dbesc($contact["nick"]),
dbesc($contact["addr"]), dbesc($contact["network"]), dbesc($contact["birthday"]),
dbesc($contact["gender"]), dbesc($contact["keywords"]), intval($contact["hide"]),
intval($contact["nsfw"]), dbesc($contact["alias"]), dbesc($contact["notify"]),
dbesc($contact["url"]), dbesc($contact["location"]), dbesc($contact["about"]),
intval($contact["generation"]), dbesc(datetime_convert()),
intval($contact["generation"]), dbesc($contact["updated"]),
dbesc($contact["server_url"]), dbesc($contact["connect"]),
dbesc(normalise_link($contact["url"])), intval($contact["generation"]));
}
@ -1656,4 +1583,82 @@ function update_gcontact_from_probe($url) {
if ($data["network"] != NETWORK_PHANTOM)
update_gcontact($data);
}
/**
* @brief Fetches users of given GNU Social server
*
* If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
*
* @param str $server Server address
*/
function gs_fetch_users($server) {
logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
$a = get_app();
$url = $server."/main/statistics";
$result = z_fetch_url($url);
if (!$result["success"])
return false;
$statistics = json_decode($result["body"]);
if (is_object($statistics->config)) {
if ($statistics->config->instance_with_ssl)
$server = "https://";
else
$server = "http://";
$server .= $statistics->config->instance_address;
$hostname = $statistics->config->instance_address;
} else {
if ($statistics->instance_with_ssl)
$server = "https://";
else
$server = "http://";
$server .= $statistics->instance_address;
$hostname = $statistics->instance_address;
}
if (is_object($statistics->users))
foreach ($statistics->users AS $nick => $user) {
$profile_url = $server."/".$user->nickname;
$contact = array("url" => $profile_url,
"name" => $user->fullname,
"addr" => $user->nickname."@".$hostname,
"nick" => $user->nickname,
"about" => $user->bio,
"network" => NETWORK_OSTATUS,
"photo" => $a->get_baseurl()."/images/person-175.jpg");
get_gcontact_id($contact);
}
}
/**
* @brief Asking GNU Social server on a regular base for their user data
*
*/
function gs_discover() {
$requery_days = intval(get_config("system", "poco_requery_days"));
$last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
$r = q("SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
dbesc(NETWORK_OSTATUS), dbesc($last_update));
if (!$r)
return;
foreach ($r AS $server) {
gs_fetch_users($server["url"]);
q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
}
}
?>

View file

@ -829,35 +829,6 @@ function qp($s) {
return str_replace ("%","=",rawurlencode($s));
}}
if(! function_exists('get_mentions')) {
/**
* @param array $item
* @return string html for mentions #FIXME: remove html
*/
function get_mentions($item) {
$o = '';
if(! strlen($item['tag']))
return $o;
$arr = explode(',',$item['tag']);
foreach($arr as $x) {
$matches = null;
if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
$o .= "\t\t" . '<link rel="ostatus:attention" href="' . $matches[1] . '" />' . "\r\n";
$o .= "\t\t" . '<link rel="mentioned" href="' . $matches[1] . '" />' . "\r\n";
}
}
if (!$item['private']) {
$o .= "\t\t".'<link rel="ostatus:attention" href="http://activityschema.org/collection/public"/>'."\r\n";
$o .= "\t\t".'<link rel="mentioned" href="http://activityschema.org/collection/public"/>'."\r\n";
}
return $o;
}}
if(! function_exists('contact_block')) {
/**
* Get html for contact block.
@ -1533,7 +1504,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
$pos = strpos($s, $spoilersearch);
$rnd = random_string(8);
$spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
$spoilerreplace = '<br /> <span id="spoiler-wrap-'.$rnd.'" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
'<blockquote class="spoiler" id="spoiler-'.$rnd.'" style="display: none;">';
$s = substr($s, 0, $pos).$spoilerreplace.substr($s, $pos+strlen($spoilersearch));
}
@ -1545,7 +1516,7 @@ function prepare_body(&$item,$attach = false, $preview = false) {
$pos = strpos($s, $authorsearch);
$rnd = random_string(8);
$authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" style="white-space:nowrap;" class="fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
$authorreplace = '<br /> <span id="author-wrap-'.$rnd.'" class="author-wrap fakelink" onclick="openClose(\'author-'.$rnd.'\');">'.sprintf(t('Click to open/close')).'</span>'.
'<blockquote class="author" id="author-'.$rnd.'" style="display: block;">';
$s = substr($s, 0, $pos).$authorreplace.substr($s, $pos+strlen($authorsearch));
}
@ -1657,54 +1628,6 @@ function get_cats_and_terms($item) {
return array($categories, $folders);
}
if(! function_exists('feed_hublinks')) {
/**
* return atom link elements for all of our hubs
* @return string hub link xml elements
*/
function feed_hublinks() {
$a = get_app();
$hub = get_config('system','huburl');
$hubxml = '';
if(strlen($hub)) {
$hubs = explode(',', $hub);
if(count($hubs)) {
foreach($hubs as $h) {
$h = trim($h);
if(! strlen($h))
continue;
if ($h === '[internal]')
$h = z_root() . '/pubsubhubbub';
$hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
}
}
}
return $hubxml;
}}
if(! function_exists('feed_salmonlinks')) {
/**
* return atom link elements for salmon endpoints
* @param string $nick user nickname
* @return string salmon link xml elements
*/
function feed_salmonlinks($nick) {
$a = get_app();
$salmon = '<link rel="salmon" href="' . xmlify(z_root() . '/salmon/' . $nick) . '" />' . "\n" ;
// old style links that status.net still needed as of 12/2010
$salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify(z_root() . '/salmon/' . $nick) . '" />' . "\n" ;
$salmon .= ' <link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify(z_root() . '/salmon/' . $nick) . '" />' . "\n" ;
return $salmon;
}}
if(! function_exists('get_plink')) {
/**
* get private link for item

View file

@ -66,6 +66,7 @@ function add_thread($itemid, $onlyshadow = false) {
unset($item[0]['id']);
$item[0]['uid'] = 0;
$item[0]['origin'] = 0;
$item[0]['contact-id'] = get_contact($item[0]['author-link'], 0);
$public_shadow = item_store($item[0], false, false, true);