Some easy to replace "q" calls have been replaced by "DBA" calls (#5632)

* Some easy to replace "q" calls have been replaced by "DBA" calls

* Simplified the GUID creation

* And one in the API ...

* And OStatus has got some DBA calls more

* Just some more replaced database calls

* The event query is now simplified

* Events are now shown again

* subthread is now using the DBA calls as well

* Some more replaced database calls

* And some more replaced database calls and prevented notices

* Better use gravity

* Some more replaced database stuff

* Some more replaced database calls in DFRN.php

* The gcontact class now has got the new DBA functions as well

* The Contact class is now changed to new database functions as well

* Small correction

* We can now delete without cascade

* One more functionality is safe for future changes
This commit is contained in:
Michael Vogel 2018-08-19 14:46:11 +02:00 committed by Hypolite Petovan
parent dfe4413463
commit 7f3fb34c24
21 changed files with 275 additions and 501 deletions

View File

@ -883,13 +883,9 @@ function feed_birthday($uid, $tz)
$tz = 'UTC'; $tz = 'UTC';
} }
$p = q( $profile = DBA::selectFirst('profile', ['dob'], ['is-default' => true, 'uid' => $uid]);
"SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1", if (DBA::isResult($profile)) {
intval($uid) $tmp_dob = substr($profile['dob'], 5);
);
if (DBA::isResult($p)) {
$tmp_dob = substr($p[0]['dob'], 5);
if (intval($tmp_dob)) { if (intval($tmp_dob)) {
$y = DateTimeFormat::timezoneNow($tz, 'Y'); $y = DateTimeFormat::timezoneNow($tz, 'Y');
$bd = $y . '-' . $tmp_dob . ' 00:00'; $bd = $y . '-' . $tmp_dob . ' 00:00';

View File

@ -631,37 +631,37 @@ function api_get_user(App $a, $contact_id = null)
// if the contact wasn't found, fetch it from the contacts with uid = 0 // if the contact wasn't found, fetch it from the contacts with uid = 0
if (!DBA::isResult($uinfo)) { if (!DBA::isResult($uinfo)) {
$r = []; if ($url == "") {
throw new BadRequestException("User not found.");
if ($url != "") {
$r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", DBA::escape(normalise_link($url)));
} }
if (DBA::isResult($r)) { $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => normalise_link($url)]);
$network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
if (DBA::isResult($contact)) {
$network_name = ContactSelector::networkToName($contact['network'], $contact['url']);
// If no nick where given, extract it from the address // If no nick where given, extract it from the address
if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) { if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
$r[0]['nick'] = api_get_nick($r[0]["url"]); $contact['nick'] = api_get_nick($contact["url"]);
} }
$ret = [ $ret = [
'id' => $r[0]["id"], 'id' => $contact["id"],
'id_str' => (string) $r[0]["id"], 'id_str' => (string) $contact["id"],
'name' => $r[0]["name"], 'name' => $contact["name"],
'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']), 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name, 'location' => ($contact["location"] != "") ? $contact["location"] : $network_name,
'description' => $r[0]["about"], 'description' => $contact["about"],
'profile_image_url' => $r[0]["micro"], 'profile_image_url' => $contact["micro"],
'profile_image_url_https' => $r[0]["micro"], 'profile_image_url_https' => $contact["micro"],
'profile_image_url_profile_size' => $r[0]["thumb"], 'profile_image_url_profile_size' => $contact["thumb"],
'profile_image_url_large' => $r[0]["photo"], 'profile_image_url_large' => $contact["photo"],
'url' => $r[0]["url"], 'url' => $contact["url"],
'protected' => false, 'protected' => false,
'followers_count' => 0, 'followers_count' => 0,
'friends_count' => 0, 'friends_count' => 0,
'listed_count' => 0, 'listed_count' => 0,
'created_at' => api_date($r[0]["created"]), 'created_at' => api_date($contact["created"]),
'favourites_count' => 0, 'favourites_count' => 0,
'utc_offset' => 0, 'utc_offset' => 0,
'time_zone' => 'UTC', 'time_zone' => 'UTC',
@ -676,12 +676,12 @@ function api_get_user(App $a, $contact_id = null)
'follow_request_sent' => false, 'follow_request_sent' => false,
'statusnet_blocking' => false, 'statusnet_blocking' => false,
'notifications' => false, 'notifications' => false,
'statusnet_profile_url' => $r[0]["url"], 'statusnet_profile_url' => $contact["url"],
'uid' => 0, 'uid' => 0,
'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true), 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
'pid' => Contact::getIdForURL($r[0]["url"], 0, true), 'pid' => Contact::getIdForURL($contact["url"], 0, true),
'self' => 0, 'self' => 0,
'network' => $r[0]["network"], 'network' => $contact["network"],
]; ];
return $ret; return $ret;
@ -4340,12 +4340,8 @@ function check_acl_input($acl_string)
foreach ($cid_array as $cid) { foreach ($cid_array as $cid) {
$cid = str_replace("<", "", $cid); $cid = str_replace("<", "", $cid);
$cid = str_replace(">", "", $cid); $cid = str_replace(">", "", $cid);
$contact = q( $condition = ['id' => $cid, 'uid' => api_user()];
"SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d", $contact_not_found |= !DBA::exists('contact', $condition);
intval($cid),
intval(api_user())
);
$contact_not_found |= !DBA::isResult($contact);
} }
return $contact_not_found; return $contact_not_found;
} }
@ -4527,7 +4523,7 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f
{ {
// get data about the api authenticated user // get data about the api authenticated user
$uri = Item::newURI(intval(api_user())); $uri = Item::newURI(intval(api_user()));
$owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user())); $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
$arr = []; $arr = [];
$arr['guid'] = System::createGUID(32); $arr['guid'] = System::createGUID(32);
@ -4537,13 +4533,13 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f
$arr['type'] = 'photo'; $arr['type'] = 'photo';
$arr['wall'] = 1; $arr['wall'] = 1;
$arr['resource-id'] = $hash; $arr['resource-id'] = $hash;
$arr['contact-id'] = $owner_record[0]['id']; $arr['contact-id'] = $owner_record['id'];
$arr['owner-name'] = $owner_record[0]['name']; $arr['owner-name'] = $owner_record['name'];
$arr['owner-link'] = $owner_record[0]['url']; $arr['owner-link'] = $owner_record['url'];
$arr['owner-avatar'] = $owner_record[0]['thumb']; $arr['owner-avatar'] = $owner_record['thumb'];
$arr['author-name'] = $owner_record[0]['name']; $arr['author-name'] = $owner_record['name'];
$arr['author-link'] = $owner_record[0]['url']; $arr['author-link'] = $owner_record['url'];
$arr['author-avatar'] = $owner_record[0]['thumb']; $arr['author-avatar'] = $owner_record['thumb'];
$arr['title'] = ""; $arr['title'] = "";
$arr['allow_cid'] = $allow_cid; $arr['allow_cid'] = $allow_cid;
$arr['allow_gid'] = $allow_gid; $arr['allow_gid'] = $allow_gid;
@ -4559,7 +4555,7 @@ function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $f
]; ];
// adds link to the thumbnail scale photo // adds link to the thumbnail scale photo
$arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']' $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
. '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]' . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
. '[/url]'; . '[/url]';
@ -5830,11 +5826,11 @@ function api_friendica_profile_show($type)
} }
// return settings, authenticated user and profiles data // return settings, authenticated user and profiles data
$self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user())); $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
$result = ['multi_profiles' => $multi_profiles ? true : false, $result = ['multi_profiles' => $multi_profiles ? true : false,
'global_dir' => $directory, 'global_dir' => $directory,
'friendica_owner' => api_get_user($a, $self[0]['nurl']), 'friendica_owner' => api_get_user($a, $self['nurl']),
'profiles' => $profiles]; 'profiles' => $profiles];
return api_format_data("friendica_profiles", $type, ['$result' => $result]); return api_format_data("friendica_profiles", $type, ['$result' => $result]);
} }

View File

@ -125,14 +125,9 @@ function notification($params)
// Check to see if there was already a tag notify or comment notify for this post. // Check to see if there was already a tag notify or comment notify for this post.
// If so don't create a second notification // If so don't create a second notification
$p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d, %d) AND `link` = '%s' AND `uid` = %d LIMIT 1", $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
intval(NOTIFY_TAGSELF), 'link' => $params['link'], 'uid' => $params['uid']];
intval(NOTIFY_COMMENT), if (DBA::exists('notify', $condition)) {
intval(NOTIFY_SHARE),
DBA::escape($params['link']),
intval($params['uid'])
);
if ($p && count($p)) {
L10n::popLang(); L10n::popLang();
return; return;
} }
@ -446,9 +441,7 @@ function notification($params)
do { do {
$dups = false; $dups = false;
$hash = random_string(); $hash = random_string();
$r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1", if (DBA::exists('notify', ['hash' => $hash])) {
DBA::escape($hash));
if (DBA::isResult($r)) {
$dups = true; $dups = true;
} }
} while ($dups == true); } while ($dups == true);
@ -478,33 +471,14 @@ function notification($params)
} }
// create notification entry in DB // create notification entry in DB
q("INSERT INTO `notify` (`hash`, `name`, `url`, `photo`, `date`, `uid`, `link`, `iid`, `parent`, `type`, `verb`, `otype`, `name_cache`) $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
values('%s', '%s', '%s', '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s')", 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
DBA::escape($datarray['hash']), 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
DBA::escape($datarray['name']), 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
DBA::escape($datarray['url']), 'name_cache' => $datarray["name_cache"]];
DBA::escape($datarray['photo']), DBA::insert('notify', $fields);
DBA::escape($datarray['date']),
intval($datarray['uid']),
DBA::escape($datarray['link']),
intval($datarray['iid']),
intval($datarray['parent']),
intval($datarray['type']),
DBA::escape($datarray['verb']),
DBA::escape($datarray['otype']),
DBA::escape($datarray["name_cache"])
);
$r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' AND `uid` = %d LIMIT 1", $notify_id = DBA::lastInsertId();
DBA::escape($hash),
intval($params['uid'])
);
if ($r) {
$notify_id = $r[0]['id'];
} else {
L10n::popLang();
return False;
}
// we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
// After we've stored everything, look again to see if there are any duplicates and if so remove them // After we've stored everything, look again to see if there are any duplicates and if so remove them
@ -529,12 +503,10 @@ function notification($params)
$itemlink = System::baseUrl().'/notify/view/'.$notify_id; $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
$msg = replace_macros($epreamble, ['$itemlink' => $itemlink]); $msg = replace_macros($epreamble, ['$itemlink' => $itemlink]);
$msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg))); $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
q("UPDATE `notify` SET `msg` = '%s', `msg_cache` = '%s' WHERE `id` = %d AND `uid` = %d",
DBA::escape($msg), $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
DBA::escape($msg_cache), $condition = ['id' => $notify_id, 'uid' => $params['uid']];
intval($notify_id), DBA::update('notify', $fields, $condition);
intval($params['uid'])
);
} }
// send email notification if notification preferences permit // send email notification if notification preferences permit
@ -548,21 +520,12 @@ function notification($params)
$id_for_parent = $params['parent']."@".$hostname; $id_for_parent = $params['parent']."@".$hostname;
// Is this the first email notification for this parent item and user? // Is this the first email notification for this parent item and user?
if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
$r = q("SELECT `id` FROM `notify-threads` WHERE `master-parent-item` = %d AND `receiver-uid` = %d LIMIT 1",
intval($params['parent']),
intval($params['uid']));
// If so, create the record of it and use a message-id smtp header.
if (!$r) {
logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG); logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG);
q("INSERT INTO `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
values(%d, %d, %d, %d)", $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
intval($notify_id), 'receiver-uid' => $params['uid'], 'parent-item' => 0];
intval($params['parent']), DBA::insert('notify-threads', $fields);
intval($params['uid']),
0);
$additional_mail_header .= "Message-ID: <${id_for_parent}>\n"; $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
$log_msg = "include/enotify: No previous notification found for this parent:\n". $log_msg = "include/enotify: No previous notification found for this parent:\n".
@ -571,7 +534,7 @@ function notification($params)
} else { } else {
// If not, just "follow" the thread. // If not, just "follow" the thread.
$additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n"; $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
logger("There's already a notification for this parent:\n".print_r($r, true), LOGGER_DEBUG); logger("There's already a notification for this parent.", LOGGER_DEBUG);
} }
} }

View File

@ -288,25 +288,30 @@ function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0
function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe') function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
{ {
$a = BaseObject::getApp();
$r = null;
if (!empty($importer)) {
$r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
intval($importer['uid'])
);
}
/* /*
* Diaspora has different message-ids in feeds than they do * Diaspora has different message-ids in feeds than they do
* through the direct Diaspora protocol. If we try and use * through the direct Diaspora protocol. If we try and use
* the feed, we'll get duplicates. So don't. * the feed, we'll get duplicates. So don't.
*/ */
if ((!DBA::isResult($r)) || $contact['network'] === Protocol::DIASPORA) { if ($contact['network'] === Protocol::DIASPORA) {
return; return;
} }
$push_url = System::baseUrl() . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id']; // Without an importer we don't have a user id - so we quit
if (empty($importer)) {
return;
}
$a = BaseObject::getApp();
$user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
// No user, no nickname, we quit
if (!DBA::isResult($user)) {
return;
}
$push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
// Use a single verify token, even if multiple hubs // Use a single verify token, even if multiple hubs
$verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string()); $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());

View File

@ -299,11 +299,7 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null)
*/ */
if (!$remote_verified) { if (!$remote_verified) {
$r = q("SELECT id FROM contact WHERE id = %d AND uid = %d AND blocked = 0 LIMIT 1", if (DBA::exists('contact', ['id' => $remote_user, 'uid' => $owner_id, 'blocked' => false])) {
intval($remote_user),
intval($owner_id)
);
if (DBA::isResult($r)) {
$remote_verified = true; $remote_verified = true;
$groups = Group::getIdsByContactId($remote_user); $groups = Group::getIdsByContactId($remote_user);
} }

View File

@ -1459,26 +1459,6 @@ function return_bytes($size_str) {
} }
} }
/**
* @return string
*/
function generate_user_guid() {
$found = true;
do {
$guid = System::createGUID(32);
$x = q("SELECT `uid` FROM `user` WHERE `guid` = '%s' LIMIT 1",
DBA::escape($guid)
);
if (!DBA::isResult($x)) {
$found = false;
}
} while ($found == true);
return $guid;
}
/** /**
* @param string $s * @param string $s
* @param boolean $strip_padding * @param boolean $strip_padding

View File

@ -771,7 +771,7 @@ function networkThreadedView(App $a, $update, $parent)
FROM `item` $sql_post_table FROM `item` $sql_post_table
STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
AND (NOT `contact`.`blocked` OR `contact`.`pending`) AND (NOT `contact`.`blocked` OR `contact`.`pending`)
AND (`item`.`parent-uri` != `item`.`uri` AND (`item`.`gravity` != %d
OR `contact`.`uid` = `item`.`uid` AND `contact`.`self` OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`) OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
@ -780,6 +780,7 @@ function networkThreadedView(App $a, $update, $parent)
AND NOT `item`.`moderated` AND $sql_extra4 AND NOT `item`.`moderated` AND $sql_extra4
$sql_extra3 $sql_extra $sql_range $sql_nets $sql_extra3 $sql_extra $sql_range $sql_nets
ORDER BY `order_date` DESC LIMIT 100", ORDER BY `order_date` DESC LIMIT 100",
intval(GRAVITY_PARENT),
intval(Contact::SHARING), intval(Contact::SHARING),
intval(Contact::FRIEND), intval(Contact::FRIEND),
intval(local_user()), intval(local_user()),
@ -791,7 +792,7 @@ function networkThreadedView(App $a, $update, $parent)
STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id` STRAIGHT_JOIN `contact` ON `contact`.`id` = `thread`.`contact-id`
AND (NOT `contact`.`blocked` OR `contact`.`pending`) AND (NOT `contact`.`blocked` OR `contact`.`pending`)
STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
AND (`item`.`parent-uri` != `item`.`uri` AND (`item`.`gravity` != %d
OR `contact`.`uid` = `item`.`uid` AND `contact`.`self` OR `contact`.`uid` = `item`.`uid` AND `contact`.`self`
OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`) OR `contact`.`rel` IN (%d, %d) AND NOT `contact`.`readonly`)
LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d LEFT JOIN `user-item` ON `user-item`.`iid` = `item`.`id` AND `user-item`.`uid` = %d
@ -800,6 +801,7 @@ function networkThreadedView(App $a, $update, $parent)
AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
$sql_extra2 $sql_extra3 $sql_range $sql_extra $sql_nets $sql_extra2 $sql_extra3 $sql_range $sql_extra $sql_nets
ORDER BY `order_date` DESC $pager_sql", ORDER BY `order_date` DESC $pager_sql",
intval(GRAVITY_PARENT),
intval(Contact::SHARING), intval(Contact::SHARING),
intval(Contact::FRIEND), intval(Contact::FRIEND),
intval(local_user()), intval(local_user()),

View File

@ -40,15 +40,12 @@ function subthread_content(App $a) {
if (!$item['wall']) { if (!$item['wall']) {
// The top level post may have been written by somebody on another system // The top level post may have been written by somebody on another system
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'uid' => $item['uid']]);
intval($item['contact-id']), if (!DBA::isResult($contact)) {
intval($item['uid'])
);
if (!DBA::isResult($r)) {
return; return;
} }
if (!$r[0]['self']) { if (!$contact['self']) {
$remote_owner = $r[0]; $remote_owner = $contact;
} }
} }
@ -79,18 +76,11 @@ function subthread_content(App $a) {
if (local_user() && (local_user() == $owner_uid)) { if (local_user() && (local_user() == $owner_uid)) {
$contact = $owner; $contact = $owner;
} else { } else {
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id'], 'uid' => $owner_uid]);
intval($_SESSION['visitor_id']), if (!DBA::isResult($contact)) {
intval($owner_uid) return;
);
if (DBA::isResult($r)) {
$contact = $r[0];
} }
} }
if (!$contact) {
return;
}
$uri = Item::newURI($owner_uid); $uri = Item::newURI($owner_uid);

View File

@ -1386,22 +1386,14 @@ class Contact extends BaseObject
// the poll url is more reliable than the profile url, as we may have // the poll url is more reliable than the profile url, as we may have
// indirect links or webfinger links // indirect links or webfinger links
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' AND NOT `pending` LIMIT 1", $condition = ['uid' => $uid, 'poll' => [$ret['poll'], normalise_link($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
intval($uid), $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
DBA::escape($ret['poll']), if (!DBA::isResult($contact)) {
DBA::escape(normalise_link($ret['poll'])), $condition = ['uid' => $uid, 'nurl' => normalise_link($url), 'network' => $ret['network'], 'pending' => false];
DBA::escape($ret['network']) $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
);
if (!DBA::isResult($r)) {
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' AND NOT `pending` LIMIT 1",
intval($uid),
DBA::escape(normalise_link($url)),
DBA::escape($ret['network'])
);
} }
if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($r)) { if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
if ($interactive) { if ($interactive) {
if (strlen($a->urlpath)) { if (strlen($a->urlpath)) {
$myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']); $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
@ -1463,14 +1455,14 @@ class Contact extends BaseObject
$writeable = 1; $writeable = 1;
} }
if (DBA::isResult($r)) { if (DBA::isResult($contact)) {
// update contact // update contact
$new_relation = (($r[0]['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING); $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
$fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false]; $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
DBA::update('contact', $fields, ['id' => $r[0]['id']]); DBA::update('contact', $fields, ['id' => $contact['id']]);
} else { } else {
$new_relation = ((in_array($ret['network'], [Protocol::MAIL])) ? self::FRIEND : self::SHARING); $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
// create contact record // create contact record
DBA::insert('contact', [ DBA::insert('contact', [
@ -1517,12 +1509,9 @@ class Contact extends BaseObject
Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force"); Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
$r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` $owner = User::getOwnerDataById($uid);
WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
intval($uid)
);
if (DBA::isResult($r)) { if (DBA::isResult($owner)) {
if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) { if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
// create a follow slap // create a follow slap
$item = []; $item = [];
@ -1533,9 +1522,9 @@ class Contact extends BaseObject
$item['guid'] = ''; $item['guid'] = '';
$item['tag'] = ''; $item['tag'] = '';
$item['attach'] = ''; $item['attach'] = '';
$slap = OStatus::salmon($item, $r[0]); $slap = OStatus::salmon($item, $owner);
if (!empty($contact['notify'])) { if (!empty($contact['notify'])) {
Salmon::slapper($r[0], $contact['notify'], $slap); Salmon::slapper($owner, $contact['notify'], $slap);
} }
} elseif ($contact['network'] == Protocol::DIASPORA) { } elseif ($contact['network'] == Protocol::DIASPORA) {
$ret = Diaspora::sendShare($a->user, $contact); $ret = Diaspora::sendShare($a->user, $contact);
@ -1672,10 +1661,8 @@ class Contact extends BaseObject
} }
} elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) { } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1", $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
intval($importer['uid']), DBA::update('contact', ['pending' => false], $condition);
DBA::escape($url)
);
} }
} }
} }
@ -1724,10 +1711,9 @@ class Contact extends BaseObject
*/ */
// Check for duplicates // Check for duplicates
$s = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1", $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
intval($rr['uid']), intval($rr['id']), DBA::escape(DateTimeFormat::utc($nextbd)), DBA::escape('birthday')); 'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
if (DBA::exists('event', $condition)) {
if (DBA::isResult($s)) {
continue; continue;
} }
@ -1741,7 +1727,6 @@ class Contact extends BaseObject
intval(0) intval(0)
); );
// update bdyear // update bdyear
q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)), q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
DBA::escape($nextbd), intval($rr['uid']), intval($rr['id']) DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])

View File

@ -550,10 +550,13 @@ class Event extends BaseObject
$fmt = L10n::t('l, F j'); $fmt = L10n::t('l, F j');
foreach ($event_result as $event) { foreach ($event_result as $event) {
$item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]); $item = Item::selectFirst(['plink', 'author-name', 'author-avatar', 'author-link'], ['id' => $event['itemid']]);
if (DBA::isResult($item)) { if (!DBA::isResult($item)) {
$event = array_merge($event, $item); // Using default values when no item had been found
$item = ['plink' => '', 'author-name' => '', 'author-avatar' => '', 'author-link' => ''];
} }
$event = array_merge($event, $item);
$start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c'); $start = $event['adjust'] ? DateTimeFormat::local($event['start'], 'c') : DateTimeFormat::utc($event['start'], 'c');
$j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j'); $j = $event['adjust'] ? DateTimeFormat::local($event['start'], 'j') : DateTimeFormat::utc($event['start'], 'j');
$day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt); $day = $event['adjust'] ? DateTimeFormat::local($event['start'], $fmt) : DateTimeFormat::utc($event['start'], $fmt);

View File

@ -98,33 +98,8 @@ class GContact
return; return;
} }
$r = q( $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
"SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1", DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
intval($cid),
intval($uid),
intval($gcid),
intval($zcid)
);
if (!DBA::isResult($r)) {
q(
"INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
intval($cid),
intval($uid),
intval($gcid),
intval($zcid),
DBA::escape(DateTimeFormat::utcNow())
);
} else {
q(
"UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
DBA::escape(DateTimeFormat::utcNow()),
intval($cid),
intval($uid),
intval($gcid),
intval($zcid)
);
}
} }
/** /**
@ -175,24 +150,19 @@ class GContact
} }
if (!isset($gcontact['network'])) { if (!isset($gcontact['network'])) {
$r = q( $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
"SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1", normalise_link($gcontact['url']), Protocol::STATUSNET];
DBA::escape(normalise_link($gcontact['url'])), $contact = DBA::selectFirst('contact', ['network'], $condition);
DBA::escape(Protocol::STATUSNET) if (DBA::isResult($contact)) {
); $gcontact['network'] = $contact["network"];
if (DBA::isResult($r)) {
$gcontact['network'] = $r[0]["network"];
} }
if (($gcontact['network'] == "") || ($gcontact['network'] == Protocol::OSTATUS)) { if (($gcontact['network'] == "") || ($gcontact['network'] == Protocol::OSTATUS)) {
$r = q( $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
"SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1", $gcontact['url'], normalise_link($gcontact['url']), Protocol::STATUSNET];
DBA::escape($gcontact['url']), $contact = DBA::selectFirst('contact', ['network'], $condition);
DBA::escape(normalise_link($gcontact['url'])), if (DBA::isResult($contact)) {
DBA::escape(Protocol::STATUSNET) $gcontact['network'] = $contact["network"];
);
if (DBA::isResult($r)) {
$gcontact['network'] = $r[0]["network"];
} }
} }
} }
@ -200,23 +170,20 @@ class GContact
$gcontact['server_url'] = ''; $gcontact['server_url'] = '';
$gcontact['network'] = ''; $gcontact['network'] = '';
$x = q( $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
"SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($gcontact['url'])]);
DBA::escape(normalise_link($gcontact['url'])) if (DBA::isResult($gcnt)) {
); if (!isset($gcontact['network']) && ($gcnt["network"] != Protocol::STATUSNET)) {
$gcontact['network'] = $gcnt["network"];
if (DBA::isResult($x)) {
if (!isset($gcontact['network']) && ($x[0]["network"] != Protocol::STATUSNET)) {
$gcontact['network'] = $x[0]["network"];
} }
if ($gcontact['updated'] <= NULL_DATE) { if ($gcontact['updated'] <= NULL_DATE) {
$gcontact['updated'] = $x[0]["updated"]; $gcontact['updated'] = $gcnt["updated"];
} }
if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) { if (!isset($gcontact['server_url']) && (normalise_link($gcnt["server_url"]) != normalise_link($gcnt["url"]))) {
$gcontact['server_url'] = $x[0]["server_url"]; $gcontact['server_url'] = $gcnt["server_url"];
} }
if (!isset($gcontact['addr'])) { if (!isset($gcontact['addr'])) {
$gcontact['addr'] = $x[0]["addr"]; $gcontact['addr'] = $gcnt["addr"];
} }
} }
@ -689,20 +656,17 @@ class GContact
} }
DBA::lock('gcontact'); DBA::lock('gcontact');
$r = q( $fields = ['id', 'last_contact', 'last_failure', 'network'];
"SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($contact["url"])]);
DBA::escape(normalise_link($contact["url"])) if (DBA::isResult($gcnt)) {
); $gcontact_id = $gcnt["id"];
if (DBA::isResult($r)) {
$gcontact_id = $r[0]["id"];
// Update every 90 days // Update every 90 days
if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) { if (in_array($gcnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
$last_failure_str = $r[0]["last_failure"]; $last_failure_str = $gcnt["last_failure"];
$last_failure = strtotime($r[0]["last_failure"]); $last_failure = strtotime($gcnt["last_failure"]);
$last_contact_str = $r[0]["last_contact"]; $last_contact_str = $gcnt["last_contact"];
$last_contact = strtotime($r[0]["last_contact"]); $last_contact = strtotime($gcnt["last_contact"]);
$doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400))); $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
} }
} else { } else {
@ -728,15 +692,11 @@ class GContact
intval($contact["generation"]) intval($contact["generation"])
); );
$r = q( $condition = ['nurl' => normalise_link($contact["url"])];
"SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2", $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
DBA::escape(normalise_link($contact["url"])) if (DBA::isResult($cnt)) {
); $gcontact_id = $cnt["id"];
$doprobing = in_array($cnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""]);
if (DBA::isResult($r)) {
$gcontact_id = $r[0]["id"];
$doprobing = in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""]);
} }
} }
DBA::unlock(); DBA::unlock();

View File

@ -111,7 +111,7 @@ class Item extends BaseObject
* @param string $activity activity string * @param string $activity activity string
* @return integer Activity index * @return integer Activity index
*/ */
private static function activityToIndex($activity) public static function activityToIndex($activity)
{ {
$index = array_search($activity, self::ACTIVITIES); $index = array_search($activity, self::ACTIVITIES);
@ -2456,6 +2456,12 @@ class Item extends BaseObject
} }
} }
/**
* This function is only used for the old Friendica app on Android that doesn't like paths with guid
* @param string $guid item guid
* @param int $uid user id
* @return array with id and nick of the item with the given guid
*/
public static function getIdAndNickByGuid($guid, $uid = 0) public static function getIdAndNickByGuid($guid, $uid = 0)
{ {
$nick = ""; $nick = "";
@ -2467,28 +2473,28 @@ class Item extends BaseObject
// Does the given user have this item? // Does the given user have this item?
if ($uid) { if ($uid) {
/// @todo This query has to be abstracted for the "uri-id" changes $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
$item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
if (DBA::isResult($item)) { if (DBA::isResult($item)) {
$id = $item["id"]; $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
$nick = $item["nickname"]; if (!DBA::isResult($user)) {
return;
}
$id = $item['id'];
$nick = $user['nickname'];
} }
} }
// Or is it anywhere on the server? // Or is it anywhere on the server?
if ($nick == "") { if ($nick == "") {
/// @todo This query has to be abstracted for the "uri-id" changes $condition = ["`guid` = ? AND `uid` != 0", $guid];
$item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item` $item = self::selectFirst(['id', 'uid'], $condition);
INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
AND NOT `item`.`private` AND `item`.`wall`
AND `item`.`guid` = ?", $guid);
if (DBA::isResult($item)) { if (DBA::isResult($item)) {
$id = $item["id"]; $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
$nick = $item["nickname"]; if (!DBA::isResult($user)) {
return;
}
$id = $item['id'];
$nick = $user['nickname'];
} }
} }
return ["nick" => $nick, "id" => $id]; return ["nick" => $nick, "id" => $id];
@ -3177,8 +3183,7 @@ class Item extends BaseObject
return; return;
} }
// Using dba::delete at this time could delete the associated item entries $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
$result = DBA::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG); logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);

View File

@ -56,13 +56,11 @@ class Mail
if (strlen($replyto)) { if (strlen($replyto)) {
$reply = true; $reply = true;
$r = q("SELECT `convid` FROM `mail` WHERE `uid` = %d AND (`uri` = '%s' OR `parent-uri` = '%s') LIMIT 1", $condition = ["`uid` = ? AND (`uri` = ? OR `parent-uri` = ?)",
intval(local_user()), local_user(), $replyto, $replyto];
DBA::escape($replyto), $mail = DBA::selectFirst('mail', ['convid'], $condition);
DBA::escape($replyto) if (DBA::isResult($mail)) {
); $convid = $mail['convid'];
if (DBA::isResult($r)) {
$convid = $r[0]['convid'];
} }
} }

View File

@ -124,12 +124,10 @@ class Profile
// fetch user tags if this isn't the default profile // fetch user tags if this isn't the default profile
if (!$pdata['is-default']) { if (!$pdata['is-default']) {
$x = q( $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
"SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1", $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
intval($pdata['profile_uid']) if (DBA::isResult($profile)) {
); $pdata['pub_keywords'] = $profile['pub_keywords'];
if ($x && count($x)) {
$pdata['pub_keywords'] = $x[0]['pub_keywords'];
} }
} }
@ -641,37 +639,26 @@ class Profile
$bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
$classtoday = ''; $classtoday = '';
$s = DBA::p( $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
"SELECT `event`.* local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
FROM `event` $s = DBA::select('event', [], $condition, ['order' => ['start']]);
INNER JOIN `item`
ON `item`.`uid` = `event`.`uid`
AND `item`.`parent-uri` = `event`.`uri`
WHERE `event`.`uid` = ?
AND `event`.`type` != 'birthday'
AND `event`.`start` < ?
AND `event`.`start` >= ?
AND `item`.`author-id` = ?
AND (`item`.`verb` = ? OR `item`.`verb` = ?)
AND `item`.`visible`
AND NOT `item`.`deleted`
ORDER BY `event`.`start` ASC",
local_user(),
DateTimeFormat::utc('now + 7 days'),
DateTimeFormat::utc('now - 1 days'),
public_contact(),
ACTIVITY_ATTEND,
ACTIVITY_ATTENDMAYBE
);
$r = []; $r = [];
if (DBA::isResult($s)) { if (DBA::isResult($s)) {
$istoday = false; $istoday = false;
$total = 0;
while ($rr = DBA::fetch($s)) { while ($rr = DBA::fetch($s)) {
$condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
'visible' => true, 'deleted' => false];
if (!Item::exists($condition)) {
continue;
}
if (strlen($rr['summary'])) { if (strlen($rr['summary'])) {
$total ++; $total++;
} }
$strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d'); $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');

View File

@ -493,7 +493,7 @@ class User
$spubkey = $sres['pubkey']; $spubkey = $sres['pubkey'];
$insert_result = DBA::insert('user', [ $insert_result = DBA::insert('user', [
'guid' => generate_user_guid(), 'guid' => System::createGUID(32),
'username' => $username, 'username' => $username,
'password' => $new_password_encoded, 'password' => $new_password_encoded,
'email' => $email, 'email' => $email,

View File

@ -211,11 +211,9 @@ class Login extends BaseModule
if (isset($_SESSION) && x($_SESSION, 'authenticated')) { if (isset($_SESSION) && x($_SESSION, 'authenticated')) {
if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) { if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) {
$r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
intval($_SESSION['visitor_id']) if (DBA::isResult($contact)) {
); self::getApp()->contact = $contact;
if (DBA::isResult($r)) {
self::getApp()->contact = $r[0];
} }
} }

View File

@ -1595,18 +1595,19 @@ class Probe
return false; return false;
} }
$x = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid)); $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]);
$r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval($uid)); $condition = ["`uid` = ? AND `server` != ''", $uid];
$mailacct = DBA::selectFirst('mailacct', ['pass', 'user'], $condition);
if (!DBA::isResult($x) || !DBA::isResult($r)) { if (!DBA::isResult($user) || !DBA::isResult($mailacct)) {
return false; return false;
} }
$mailbox = Email::constructMailboxName($r[0]); $mailbox = Email::constructMailboxName($mailacct);
$password = ''; $password = '';
openssl_private_decrypt(hex2bin($r[0]['pass']), $password, $x[0]['prvkey']); openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']);
$mbox = Email::connect($mailbox, $r[0]['user'], $password); $mbox = Email::connect($mailbox, $mailacct['user'], $password);
if (!$mbox) { if (!$mbox) {
return false; return false;
} }
@ -1659,7 +1660,6 @@ class Probe
if (!empty($mbox)) { if (!empty($mbox)) {
imap_close($mbox); imap_close($mbox);
} }
return $data; return $data;
} }

View File

@ -1056,13 +1056,10 @@ class DFRN
} }
foreach ($mentioned as $mention) { foreach ($mentioned as $mention) {
$r = q( $condition = ['uid' => $owner["uid"], 'nurl' => normalise_link($mention)];
"SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'", $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
intval($owner["uid"]),
DBA::escape(normalise_link($mention))
);
if (DBA::isResult($r) && ($r[0]["forum"] || $r[0]["prv"])) { if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
XML::addElement( XML::addElement(
$doc, $doc,
$entry, $entry,
@ -1232,14 +1229,11 @@ class DFRN
$final_dfrn_id = ''; $final_dfrn_id = '';
if ($perm) { if ($perm) {
if ((($perm == 'rw') && (! intval($contact['writable']))) if ((($perm == 'rw') && !intval($contact['writable']))
|| (($perm == 'r') && (intval($contact['writable']))) || (($perm == 'r') && intval($contact['writable']))
) { ) {
q( DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
"update contact set writable = %d where id = %d",
intval(($perm == 'rw') ? 1 : 0),
intval($contact['id'])
);
$contact['writable'] = (string) 1 - intval($contact['writable']); $contact['writable'] = (string) 1 - intval($contact['writable']);
} }
} }
@ -1480,15 +1474,9 @@ class DFRN
private static function birthdayEvent($contact, $birthday) private static function birthdayEvent($contact, $birthday)
{ {
// Check for duplicates // Check for duplicates
$r = q( $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
"SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1", 'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
intval($contact['uid']), if (DBA::exists('event', $condition)) {
intval($contact['id']),
DBA::escape(DateTimeFormat::utc($birthday)),
DBA::escape('birthday')
);
if (DBA::isResult($r)) {
return; return;
} }
@ -1910,13 +1898,6 @@ class DFRN
// Does our member already have a friend matching this description? // Does our member already have a friend matching this description?
$r = q(
"SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
DBA::escape($suggest["name"]),
DBA::escape(normalise_link($suggest["url"])),
intval($suggest["uid"])
);
/* /*
* The valid result means the friend we're about to send a friend * The valid result means the friend we're about to send a friend
* suggestion already has them in their contact, which means no further * suggestion already has them in their contact, which means no further
@ -1924,37 +1905,29 @@ class DFRN
* *
* @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
*/ */
if (DBA::isResult($r)) { $condition = ['name' => $suggest["name"], 'nurl' => normalise_link($suggest["url"]),
'uid' => $suggest["uid"]];
if (DBA::exists('contact', $condition)) {
return false; return false;
} }
// Do we already have an fcontact record for this person? // Do we already have an fcontact record for this person?
$fid = 0; $fid = 0;
$r = q( $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
"SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
DBA::escape($suggest["url"]), if (DBA::isResult($fcontact)) {
DBA::escape($suggest["name"]), $fid = $fcontact["id"];
DBA::escape($suggest["request"])
);
if (DBA::isResult($r)) {
$fid = $r[0]["id"];
// OK, we do. Do we already have an introduction for this person ? // OK, we do. Do we already have an introduction for this person?
$r = q( if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
"SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1", /*
intval($suggest["uid"]), * The valid result means the friend we're about to send a friend
intval($fid) * suggestion already has them in their contact, which means no further
); * action is required.
*
/* * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
* The valid result means the friend we're about to send a friend */
* suggestion already has them in their contact, which means no further
* action is required.
*
* @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
*/
if (DBA::isResult($r)) {
return false; return false;
} }
} }
@ -1967,18 +1940,15 @@ class DFRN
DBA::escape($suggest["request"]) DBA::escape($suggest["request"])
); );
} }
$r = q(
"SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1", $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
DBA::escape($suggest["url"]), $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
DBA::escape($suggest["name"]),
DBA::escape($suggest["request"])
);
/* /*
* If no record in fcontact is found, below INSERT statement will not * If no record in fcontact is found, below INSERT statement will not
* link an introduction to it. * link an introduction to it.
*/ */
if (!DBA::isResult($r)) { if (!DBA::isResult($fcontact)) {
// Database record did not get created. Quietly give up. // Database record did not get created. Quietly give up.
killme(); killme();
} }
@ -2646,13 +2616,10 @@ class DFRN
$ev["guid"] = $item["guid"]; $ev["guid"] = $item["guid"];
$ev["plink"] = $item["plink"]; $ev["plink"] = $item["plink"];
$r = q( $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
"SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", $event = DBA::selectFirst('event', ['id'], $condition);
DBA::escape($item["uri"]), if (DBA::isResult($event)) {
intval($importer["importer_uid"]) $ev["id"] = $event["id"];
);
if (DBA::isResult($r)) {
$ev["id"] = $r[0]["id"];
} }
$event_id = Event::store($ev); $event_id = Event::store($ev);
@ -3035,23 +3002,21 @@ class DFRN
return false; return false;
} }
$u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
intval($uid) if (!DBA::isResult($user)) {
);
if (!DBA::isResult($u)) {
return false; return false;
} }
$community_page = ($u[0]['page-flags'] == Contact::PAGE_COMMUNITY); $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
$prvgroup = ($u[0]['page-flags'] == Contact::PAGE_PRVGROUP); $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
$link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']); $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
/* /*
* Diaspora uses their own hardwired link URL in @-tags * Diaspora uses their own hardwired link URL in @-tags
* instead of the one we supply with webfinger * instead of the one we supply with webfinger
*/ */
$dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']); $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
$cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER); $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
if ($cnt) { if ($cnt) {

View File

@ -970,13 +970,10 @@ class Diaspora
logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG); logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
if ($pcontact_id != 0) { if ($pcontact_id != 0) {
$r = q( $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
"SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
intval($pcontact_id)
);
if (DBA::isResult($r)) { if (DBA::isResult($contact) && !empty($contact["addr"])) {
return strtolower($r[0]["addr"]); return strtolower($contact["addr"]);
} }
} }
@ -1788,12 +1785,7 @@ class Diaspora
DBA::lock('mail'); DBA::lock('mail');
$r = q( if (DBA::exists('mail', ['guid' => $msg_guid, 'uid' => $importer["uid"]])) {
"SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
DBA::escape($msg_guid),
intval($importer["uid"])
);
if (DBA::isResult($r)) {
logger("duplicate message already delivered.", LOGGER_DEBUG); logger("duplicate message already delivered.", LOGGER_DEBUG);
return false; return false;
} }
@ -1868,16 +1860,8 @@ class Diaspora
return false; return false;
} }
$conversation = null; $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
if (!DBA::isResult($conversation)) {
$c = q(
"SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
intval($importer["uid"]),
DBA::escape($guid)
);
if ($c)
$conversation = $c[0];
else {
$r = q( $r = q(
"INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`) "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')", VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
@ -1890,15 +1874,7 @@ class Diaspora
DBA::escape($participants) DBA::escape($participants)
); );
if ($r) { if ($r) {
$c = q( $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
"SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
intval($importer["uid"]),
DBA::escape($guid)
);
}
if ($c) {
$conversation = $c[0];
} }
} }
if (!$conversation) { if (!$conversation) {
@ -2049,14 +2025,10 @@ class Diaspora
$conversation = null; $conversation = null;
$c = q( $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
"SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1", $conversation = DBA::selectFirst('conv', [], $condition);
intval($importer["uid"]),
DBA::escape($conversation_guid) if (!DBA::isResult($conversation)) {
);
if ($c) {
$conversation = $c[0];
} else {
logger("conversation not available."); logger("conversation not available.");
return false; return false;
} }
@ -2075,12 +2047,7 @@ class Diaspora
DBA::lock('mail'); DBA::lock('mail');
$r = q( if (DBA::exists('mail', ['guid' => $guid, 'uid' => $importer["uid"]])) {
"SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
DBA::escape($guid),
intval($importer["uid"])
);
if (DBA::isResult($r)) {
logger("duplicate message already delivered.", LOGGER_DEBUG); logger("duplicate message already delivered.", LOGGER_DEBUG);
return false; return false;
} }
@ -2363,10 +2330,10 @@ class Diaspora
// If we are now friends, we are sending a share message. // If we are now friends, we are sending a share message.
// Normally we needn't to do so, but the first message could have been vanished. // Normally we needn't to do so, but the first message could have been vanished.
if (in_array($contact["rel"], [Contact::FRIEND])) { if (in_array($contact["rel"], [Contact::FRIEND])) {
$u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"])); $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
if ($u) { if (DBA::isResult($user)) {
logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG); logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
$ret = self::sendShare($u[0], $contact); $ret = self::sendShare($user, $contact);
} }
} }
return true; return true;
@ -2485,10 +2452,10 @@ class Diaspora
intval($contact_record["id"]) intval($contact_record["id"])
); );
$u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"])); $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
if ($u) { if (DBA::isResult($user)) {
logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG); logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
$ret = self::sendShare($u[0], $contact_record); $ret = self::sendShare($user, $contact_record);
// Send the profile data, maybe it weren't transmitted before // Send the profile data, maybe it weren't transmitted before
self::sendProfile($importer["uid"], [$contact_record]); self::sendProfile($importer["uid"], [$contact_record]);
@ -3830,19 +3797,13 @@ class Diaspora
logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG); logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
// fetch the original signature // fetch the original signature
$fields = ['signed_text', 'signature', 'signer'];
$r = q( $signature = DBA::selectFirst('sign', $fields, ['iid' => $item["id"]]);
"SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1", if (!DBA::isResult($signature)) {
intval($item["id"])
);
if (!$r) {
logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG); logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
return false; return false;
} }
$signature = $r[0];
// Old way - is used by the internal Friendica functions // Old way - is used by the internal Friendica functions
/// @todo Change all signatur storing functions to the new format /// @todo Change all signatur storing functions to the new format
if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) { if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
@ -3923,17 +3884,11 @@ class Diaspora
{ {
$myaddr = self::myHandle($owner); $myaddr = self::myHandle($owner);
$r = q( $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
"SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1", if (!DBA::isResult($cnv)) {
intval($item["convid"]),
intval($item["uid"])
);
if (!DBA::isResult($r)) {
logger("conversation not found."); logger("conversation not found.");
return; return;
} }
$cnv = $r[0];
$conv = [ $conv = [
"author" => $cnv["creator"], "author" => $cnv["creator"],
@ -4168,12 +4123,12 @@ class Diaspora
return false; return false;
} }
$r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid'])); $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $contact["uid"]]);
if (!DBA::isResult($r)) { if (!DBA::isResult($user)) {
return false; return false;
} }
$contact["uprvkey"] = $r[0]['prvkey']; $contact["uprvkey"] = $user['prvkey'];
$item = Item::selectFirst([], ['id' => $post_id]); $item = Item::selectFirst([], ['id' => $post_id]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {

View File

@ -1597,12 +1597,9 @@ class OStatus
} }
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
$r = q( $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => normalise_link($url)]);
"SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
DBA::escape(normalise_link($url))
);
if (DBA::isResult($r)) { if (DBA::isResult($r)) {
$contact = $r[0]; $contact = $gcontact;
$contact["uid"] = -1; $contact["uid"] = -1;
$contact["success_update"] = $contact["updated"]; $contact["success_update"] = $contact["updated"];
} }
@ -1803,14 +1800,11 @@ class OStatus
$item['follow'] = $contact['alias']; $item['follow'] = $contact['alias'];
} }
$r = q( $condition = ['uid' => $owner['uid'], 'nurl' => normalise_link($contact["url"])];
"SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'", $user_contact = DBA::selectFirst('contact', ['id'], $condition);
intval($owner['uid']),
DBA::escape(normalise_link($contact["url"]))
);
if (DBA::isResult($r)) { if (DBA::isResult($user_contact)) {
$connect_id = $r[0]['id']; $connect_id = $user_contact['id'];
} else { } else {
$connect_id = 0; $connect_id = 0;
} }

View File

@ -275,10 +275,6 @@ class CronJobs
} }
} }
// 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");
// There was an issue where the nick vanishes from the contact table // There was an issue where the nick vanishes from the contact table
q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''"); q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");